{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "254e304e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:24.522643Z", "iopub.status.busy": "2025-03-25T05:09:24.522416Z", "iopub.status.idle": "2025-03-25T05:09:24.694110Z", "shell.execute_reply": "2025-03-25T05:09:24.693670Z" } }, "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 = \"GSE42986\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Epilepsy\"\n", "in_cohort_dir = \"../../input/GEO/Epilepsy/GSE42986\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Epilepsy/GSE42986.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Epilepsy/gene_data/GSE42986.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Epilepsy/clinical_data/GSE42986.csv\"\n", "json_path = \"../../output/preprocess/Epilepsy/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6f45cbef", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ec102768", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:24.695578Z", "iopub.status.busy": "2025-03-25T05:09:24.695428Z", "iopub.status.idle": "2025-03-25T05:09:24.761033Z", "shell.execute_reply": "2025-03-25T05:09:24.760641Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptome profiling in human primary mitochondrial respiratory chain disease\"\n", "!Series_summary\t\"Primary mitochondrial respiratory chain (RC) diseases are heterogeneous in etiology and manifestations but collectively impair cellular energy metabolism. To identify a common cellular response to RC disease, systems biology level transcriptome investigations were performed in human RC disease skeletal muscle and fibroblasts. Global transcriptional and post-transcriptional dysregulation in a tissue-specific fashion was identified across diverse RC complex and genetic etiologies. RC disease muscle was characterized by decreased transcription of cytosolic ribosomal proteins to reduce energy-intensive anabolic processes, increased transcription of mitochondrial ribosomal proteins, shortened 5'-UTRs to improve translational efficiency, and stabilization of 3'-UTRs containing AU-rich elements. These same modifications in a reversed direction typified RC disease fibroblasts. RC disease also dysregulated transcriptional networks related to basic nutrient-sensing signaling pathways, which collectively mediate many aspects of tissue-specific cellular responses to primary RC disease. These findings support the utility of a systems biology approach to improve mechanistic understanding of mitochondrial RC disease.\"\n", "!Series_summary\t\"To identify a common cellular response to primary RC that might improve mechanistic understanding and lead to targeted therapies for human RC disease, we performed collective transcriptome profiling in skeletal muscle biopsy specimens and fibroblast cell lines (FCLs) of a diverse cohort of human mitochondrial disease subjects relative to controls. Systems biology investigations of common cellular responses to primary RC disease revealed a collective pattern of transcriptional, post-transcriptional and translational dysregulation occurring in a highly tissue-specific fashion.\"\n", "!Series_overall_design\t\"Affymetrix Human Exon 1.0ST microarray analysis was performed on 29 skeletal muscle samples and Fibroblast cell lines from mitochondrial disease patients and age- and gender-matched controls.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Skeletal muscle', 'tissue: fibroblast cell line'], 1: ['respiratory chain complex deficiency: No Respiratory Chain Complex Deficiency', 'respiratory chain complex deficiency: Complexes I and III', 'respiratory chain complex deficiency: Complex IV', 'respiratory chain complex deficiency: Complexes II and III', 'respiratory chain complex deficiency: Not measured; 87% mtDNA depletion in muscle', 'respiratory chain complex deficiency: Complex IV; 70% mtDNA depletion in liver', 'respiratory chain complex deficiency: Complex IV; 93% mtDNA depletion in muscle', 'respiratory chain complex deficiency: Complexes I and IV', 'respiratory chain complex deficiency: Complex I', 'respiratory chain complex deficiency: Complex I and IV', 'respiratory chain complex deficiency in muscle: Not Determined', 'respiratory chain complex deficiency in muscle: Complex I+III Deficiency', 'respiratory chain complex deficiency in muscle: No Respiratory Chain Complex Deficiency', 'respiratory chain complex deficiency in muscle: Complexes I and III', 'respiratory chain complex deficiency in muscle: Complex IV', 'respiratory chain complex deficiency in muscle: Complexes II and III', 'respiratory chain complex deficiency in muscle: Complex IV; 93% mtDNA depletion in muscle', 'respiratory chain complex deficiency in muscle: Complex I'], 2: ['gender: F', 'gender: M'], 3: ['age (years): 0.76', 'age (years): 20', 'age (years): 16', 'age (years): 1', 'age (years): 0.75', 'age (years): 3', 'age (years): 0.2', 'age (years): 0.9', 'age (years): 2', 'age (years): 6', 'age (years): 10', 'age (years): 4', 'age (years): 0.3', 'age (years): 8', 'age (years): 72', 'age (years): 54', 'age (years): 23', 'age (years): 60', 'age (years): 67', 'age (years): 59', 'age (years): 11', 'age (years): 46', 'age (years): 42', 'age (years): not obtained', 'age (years): 5', 'age (years): 30', 'age (years): 36', 'age (years): 39', 'age (years): 0.1', 'age (years): 0.7'], 4: ['informatic analysis group: Control Group', 'informatic analysis group: Mito Disease Group', 'informatic analysis group: Excluded - poor quality', 'informatic analysis group: Excluded - sample outlier']}\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": "492f1a8e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "3a75dc92", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:24.762159Z", "iopub.status.busy": "2025-03-25T05:09:24.762051Z", "iopub.status.idle": "2025-03-25T05:09:24.766702Z", "shell.execute_reply": "2025-03-25T05:09:24.766336Z" } }, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import re\n", "from typing import Dict, Any, List, Callable, Optional\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains transcriptome profiling using\n", "# Affymetrix Human Exon 1.0ST microarray, which likely contains gene expression data.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# Examining the data more carefully, this dataset seems to be about mitochondrial respiratory chain disease,\n", "# not epilepsy. The trait variable in our context is Epilepsy, but we don't see information about epilepsy \n", "# in the sample characteristics.\n", "# Looking at the background information and sample characteristics dictionary, this doesn't appear to be\n", "# an epilepsy-related dataset, so trait data is not available.\n", "trait_row = None\n", "\n", "# Age\n", "# Row 3 contains age information\n", "age_row = 3\n", "\n", "# Gender\n", "# Row 2 contains gender information\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert trait status to binary.\n", " Not used in this dataset as trait data is not available.\n", " \"\"\"\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age to continuous numeric value.\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Handle \"not obtained\" case\n", " if value.lower() == \"not obtained\":\n", " return None\n", " \n", " # Try to extract numeric value\n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender to binary.\n", " 0 = Female\n", " 1 = Male\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary\n", " if value.upper() == 'F':\n", " return 0\n", " elif value.upper() == 'M':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Use the validate_and_save_cohort_info function to save initial filtering results\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 don't have trait data available for this cohort\n", "# and we'll skip the clinical feature extraction step\n", "if trait_row is not None:\n", " # This code won't execute as trait_row is None\n", " # But would be used if trait data were available\n", " pass\n" ] }, { "cell_type": "markdown", "id": "9a6b3095", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "8f633634", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:24.767894Z", "iopub.status.busy": "2025-03-25T05:09:24.767632Z", "iopub.status.idle": "2025-03-25T05:09:24.856526Z", "shell.execute_reply": "2025-03-25T05:09:24.856005Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Epilepsy/GSE42986/GSE42986_family.soft.gz\n", "Matrix file: ../../input/GEO/Epilepsy/GSE42986/GSE42986_series_matrix.txt.gz\n", "Found the matrix table marker in the file.\n", "Gene data shape: (20788, 53)\n", "First 20 gene/probe identifiers:\n", "['100009676_at', '10000_at', '10001_at', '10002_at', '100033416_at', '100033422_at', '100033423_at', '100033424_at', '100033425_at', '100033426_at', '100033428_at', '100033431_at', '100033434_at', '100033436_at', '100033438_at', '100033439_at', '100033444_at', '100033800_at', '100033806_at', '100033819_at']\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": "da255748", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "74f324d1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:24.857820Z", "iopub.status.busy": "2025-03-25T05:09:24.857705Z", "iopub.status.idle": "2025-03-25T05:09:24.859766Z", "shell.execute_reply": "2025-03-25T05:09:24.859455Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the gene expression data\n", "# Looking at the format of the identifiers: '100009676_at', '10000_at', etc.\n", "# These appear to be Affymetrix probe IDs (with _at suffix) \n", "# rather than standard human gene symbols\n", "\n", "# Affymetrix probe IDs need to be mapped to standard gene symbols\n", "# for proper biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "471ba608", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "51bd4d63", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:24.860790Z", "iopub.status.busy": "2025-03-25T05:09:24.860685Z", "iopub.status.idle": "2025-03-25T05:09:25.981721Z", "shell.execute_reply": "2025-03-25T05:09:25.981160Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'Gene_ID', 'ORF', 'Symbol', 'Chromosome', 'RefSeq_ID', 'Num_Probes', 'Full_Name']\n", "{'ID': ['1_at', '2_at', '9_at', '10_at', '12_at'], 'Gene_ID': ['1', '2', '9', '10', '12'], 'ORF': ['A1BG', 'A2M', 'NAT1', 'NAT2', 'SERPINA3'], 'Symbol': ['A1BG', 'A2M', 'NAT1', 'NAT2', 'SERPINA3'], 'Chromosome': ['19', '12', '8', '8', '14'], 'RefSeq_ID': ['NM_130786;NP_570602', 'NM_000014;NP_000005', 'NM_000662;NM_001160170;NM_001160171;NM_001160172;NM_001160173;NM_001160174;NM_001160175;NM_001160176;NM_001160179;NP_000653;NP_001153642;NP_001153643;NP_001153644;NP_001153645;NP_001153646;NP_001153647;NP_001153648;NP_001153651', 'NM_000015;NP_000006', 'NM_001085;NP_001076'], 'Num_Probes': [47.0, 167.0, 74.0, 20.0, 56.0], 'Full_Name': ['alpha-1-B glycoprotein', 'alpha-2-macroglobulin', 'N-acetyltransferase 1 (arylamine N-acetyltransferase)', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'serpin peptidase inhibitor, clade A (alpha-1 antiproteinase, antitrypsin), member 3']}\n", "\n", "Sample of Description column (first 5 rows):\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", "# Based on the preview, 'ID' appears to be the probe ID and 'Description' contains gene names\n", "# Display more samples from the Description column to better understand the format\n", "print(\"\\nSample of Description column (first 5 rows):\")\n", "if 'Description' in gene_annotation.columns:\n", " for i in range(min(5, len(gene_annotation))):\n", " print(f\"Row {i}: {gene_annotation['Description'].iloc[i]}\")\n" ] }, { "cell_type": "markdown", "id": "3c3c2581", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "b5bd607f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:25.983239Z", "iopub.status.busy": "2025-03-25T05:09:25.983112Z", "iopub.status.idle": "2025-03-25T05:09:26.645082Z", "shell.execute_reply": "2025-03-25T05:09:26.644703Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Mapping probe IDs to gene symbols...\n", "Gene mapping dataframe shape: (20788, 2)\n", "Sample of gene mapping (first 5 rows):\n", "{'ID': ['1_at', '2_at', '9_at', '10_at', '12_at'], 'Gene': ['A1BG', 'A2M', 'NAT1', 'NAT2', 'SERPINA3']}\n", "\n", "Gene expression data after mapping: (19870, 53)\n", "First 10 gene symbols after mapping:\n", "['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AA06', 'AAA1']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after normalization: (19636, 53)\n", "First 10 normalized gene symbols:\n", "['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AA06', 'AAA1', 'AAAS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Saved processed gene expression data to: ../../output/preprocess/Epilepsy/gene_data/GSE42986.csv\n" ] } ], "source": [ "# 1. Determine which columns to use for mapping\n", "# Based on the previews:\n", "# - 'ID' in gene_annotation contains probe IDs (like '1_at', '2_at', etc.)\n", "# - 'Symbol' contains gene symbols (like 'A1BG', 'A2M', etc.)\n", "print(\"\\nMapping probe IDs to gene symbols...\")\n", "prob_col = 'ID' # Column containing the probe identifiers\n", "gene_col = 'Symbol' # Column containing the gene symbols\n", "\n", "# 2. Get a gene mapping dataframe by extracting the two columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n", "print(\"Sample of gene mapping (first 5 rows):\")\n", "print(preview_df(gene_mapping, n=5))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene-level data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"\\nGene expression data after mapping: {gene_data.shape}\")\n", "print(\"First 10 gene symbols after mapping:\")\n", "print(list(gene_data.index[:10]))\n", "\n", "# Normalize gene symbols to ensure consistency across the dataset\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"\\nGene expression data after normalization: {gene_data.shape}\")\n", "print(\"First 10 normalized gene symbols:\")\n", "print(list(gene_data.index[:10]))\n", "\n", "# Save the processed 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\"\\nSaved processed gene expression data to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "1d52cb77", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "2b5915ee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:26.646558Z", "iopub.status.busy": "2025-03-25T05:09:26.646431Z", "iopub.status.idle": "2025-03-25T05:09:27.206117Z", "shell.execute_reply": "2025-03-25T05:09:27.205730Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (19636, 53)\n", "Gene data shape after normalization: (19636, 53)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Epilepsy/gene_data/GSE42986.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: GSE42986. 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 }