{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "aa2e2ad3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:29.835446Z", "iopub.status.busy": "2025-03-25T05:52:29.835336Z", "iopub.status.idle": "2025-03-25T05:52:30.000384Z", "shell.execute_reply": "2025-03-25T05:52:30.000025Z" } }, "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 = \"Mitochondrial_Disorders\"\n", "cohort = \"GSE42986\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mitochondrial_Disorders\"\n", "in_cohort_dir = \"../../input/GEO/Mitochondrial_Disorders/GSE42986\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mitochondrial_Disorders/GSE42986.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mitochondrial_Disorders/gene_data/GSE42986.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mitochondrial_Disorders/clinical_data/GSE42986.csv\"\n", "json_path = \"../../output/preprocess/Mitochondrial_Disorders/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bb1e5c9e", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "97723928", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:30.001906Z", "iopub.status.busy": "2025-03-25T05:52:30.001760Z", "iopub.status.idle": "2025-03-25T05:52:30.065425Z", "shell.execute_reply": "2025-03-25T05:52:30.065110Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE42986_family.soft.gz', 'GSE42986_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Mitochondrial_Disorders/GSE42986/GSE42986_family.soft.gz\n", "Matrix file: ../../input/GEO/Mitochondrial_Disorders/GSE42986/GSE42986_series_matrix.txt.gz\n", "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": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "04685993", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "8af41404", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:30.066543Z", "iopub.status.busy": "2025-03-25T05:52:30.066432Z", "iopub.status.idle": "2025-03-25T05:52:30.078059Z", "shell.execute_reply": "2025-03-25T05:52:30.077761Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{1: [nan, nan, nan], 2: [nan, nan, nan], 3: [nan, nan, nan]}\n", "Clinical data saved to ../../output/preprocess/Mitochondrial_Disorders/clinical_data/GSE42986.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background info, this dataset contains transcriptome profiling data \n", "# from Affymetrix Human Exon 1.0ST microarray, so it's suitable for our analysis\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# For trait: Mitochondrial Disorders are reflected in respiratory chain deficiency\n", "trait_row = 1 # Key for respiratory chain complex deficiency\n", "\n", "# For age: available in key 3\n", "age_row = 3\n", "\n", "# For gender: available in key 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert respiratory chain complex deficiency into binary (0 = No deficiency, 1 = Has deficiency)\n", " \"\"\"\n", " if not value or \":\" not in value:\n", " return None\n", " \n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # No deficiency cases\n", " if \"No Respiratory Chain Complex Deficiency\" in value:\n", " return 0\n", " # All other cases with respiratory chain complex deficiency\n", " elif \"Complex\" in value or \"Complexes\" in value or \"mtDNA depletion\" in value:\n", " return 1\n", " # If we can't determine\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age to continuous value (float)\n", " \"\"\"\n", " if not value or \":\" not in value:\n", " return None\n", " \n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if value.lower() == \"not obtained\":\n", " return None\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender to binary (0 = Female, 1 = Male)\n", " \"\"\"\n", " if not value or \":\" not in value:\n", " return None\n", " \n", " value = value.split(\":\", 1)[1].strip()\n", " \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", "# Check if trait data is available (trait_row is not None)\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\n", "if trait_row is not None:\n", " # The sample characteristics dictionary from the output shows unique values\n", " # We need to read the actual data from the series matrix file\n", " \n", " # First, let's load the matrix file to extract the clinical data\n", " matrix_file = f\"{in_cohort_dir}/GSE42986_series_matrix.txt.gz\"\n", " \n", " # Read the matrix file to get clinical data\n", " with gzip.open(matrix_file, 'rt') as file:\n", " lines = []\n", " # Read the file until we reach the sample data\n", " for line in file:\n", " if line.startswith('!Sample_'):\n", " lines.append(line.strip())\n", " # Stop when we reach the table data\n", " if line.startswith('!series_matrix_table_begin'):\n", " break\n", " \n", " # Parse the sample information into a proper DataFrame\n", " sample_ids = []\n", " sample_data = {}\n", " \n", " for line in lines:\n", " if line.startswith('!Sample_geo_accession'):\n", " sample_ids = line.split('\\t')[1:]\n", " for i in range(len(sample_ids)):\n", " sample_data[i] = {}\n", " \n", " elif line.startswith('!Sample_characteristics_ch1'):\n", " values = line.split('\\t')[1:]\n", " for i, value in enumerate(values):\n", " if i < len(sample_ids):\n", " # Extract the key (before the :)\n", " if ':' in value:\n", " key_part = value.split(':', 1)[0].strip()\n", " # Store the characteristic under the appropriate row\n", " if key_part == 'respiratory chain complex deficiency' or key_part == 'respiratory chain complex deficiency in muscle':\n", " if 1 not in sample_data[i]:\n", " sample_data[i][1] = []\n", " sample_data[i][1].append(value)\n", " elif key_part == 'gender':\n", " if 2 not in sample_data[i]:\n", " sample_data[i][2] = []\n", " sample_data[i][2].append(value)\n", " elif key_part == 'age (years)':\n", " if 3 not in sample_data[i]:\n", " sample_data[i][3] = []\n", " sample_data[i][3].append(value)\n", " \n", " # Create a DataFrame from the parsed data\n", " clinical_data_rows = []\n", " for i in range(len(sample_ids)):\n", " row_data = {}\n", " for row_key in [1, 2, 3]: # trait_row, gender_row, age_row\n", " if row_key in sample_data[i] and sample_data[i][row_key]:\n", " row_data[row_key] = sample_data[i][row_key][0] # Take the first value\n", " else:\n", " row_data[row_key] = None\n", " clinical_data_rows.append(row_data)\n", " \n", " clinical_data = pd.DataFrame(clinical_data_rows)\n", " \n", " # Extract clinical features using the library function\n", " selected_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted features\n", " preview = preview_df(selected_features)\n", " print(\"Preview of extracted 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_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "234004cf", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4a6d24da", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:30.079114Z", "iopub.status.busy": "2025-03-25T05:52:30.078996Z", "iopub.status.idle": "2025-03-25T05:52:30.173301Z", "shell.execute_reply": "2025-03-25T05:52:30.172896Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n", "\n", "Gene data extraction result:\n", "Number of rows: 20788\n", "First 20 gene/probe identifiers:\n", "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '100033416_at',\n", " '100033422_at', '100033423_at', '100033424_at', '100033425_at',\n", " '100033426_at', '100033428_at', '100033431_at', '100033434_at',\n", " '100033436_at', '100033438_at', '100033439_at', '100033444_at',\n", " '100033800_at', '100033806_at', '100033819_at'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "f4826e52", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "c91343f3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:30.174701Z", "iopub.status.busy": "2025-03-25T05:52:30.174583Z", "iopub.status.idle": "2025-03-25T05:52:30.176461Z", "shell.execute_reply": "2025-03-25T05:52:30.176172Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers format: '100009676_at', '10000_at', etc.\n", "# These appear to be Affymetrix probe IDs (with the \"_at\" suffix), \n", "# not standard human gene symbols.\n", "# Affymetrix probe IDs need to be mapped to standard gene symbols for analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "8193216d", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "c40822af", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:30.177594Z", "iopub.status.busy": "2025-03-25T05:52:30.177488Z", "iopub.status.idle": "2025-03-25T05:52:31.308103Z", "shell.execute_reply": "2025-03-25T05:52:31.307625Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\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" ] } ], "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": "c006cdc5", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "cfa76478", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:31.309772Z", "iopub.status.busy": "2025-03-25T05:52:31.309528Z", "iopub.status.idle": "2025-03-25T05:52:31.972118Z", "shell.execute_reply": "2025-03-25T05:52:31.971658Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview (first 5 rows):\n", " ID Gene\n", "0 1_at A1BG\n", "1 2_at A2M\n", "2 9_at NAT1\n", "3 10_at NAT2\n", "4 12_at SERPINA3\n", "Total number of mappings: 20788\n", "\n", "Gene expression data after mapping:\n", "Number of genes: 19870\n", "First few genes:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT',\n", " 'AA06', 'AAA1'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after normalization:\n", "Number of genes after normalization: 19636\n", "First few normalized genes:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AA06',\n", " 'AAA1', 'AAAS'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Mitochondrial_Disorders/gene_data/GSE42986.csv\n" ] } ], "source": [ "# 1. Determine which columns in gene annotation correspond to probe IDs and gene symbols\n", "# From the preview, we can see:\n", "# - 'ID' contains values like '1_at', '2_at' which match the format of our gene expression data\n", "# - 'Symbol' contains standard gene symbols like 'A1BG', 'A2M'\n", "\n", "# 2. Create a mapping dataframe with the ID (probe) and Symbol (gene) columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "\n", "print(\"Gene mapping preview (first 5 rows):\")\n", "print(gene_mapping.head())\n", "print(f\"Total number of mappings: {len(gene_mapping)}\")\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene-level expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "print(\"First few genes:\")\n", "print(gene_data.index[:10])\n", "\n", "# Normalize gene symbols to handle gene synonym variations\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(\"\\nGene expression data after normalization:\")\n", "print(f\"Number of genes after normalization: {len(gene_data)}\")\n", "print(\"First few normalized genes:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "f5f1b33e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "facba161", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:31.973621Z", "iopub.status.busy": "2025-03-25T05:52:31.973477Z", "iopub.status.idle": "2025-03-25T05:52:40.818906Z", "shell.execute_reply": "2025-03-25T05:52:40.817726Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (19636, 53)\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", "Clinical data preview:\n", "{'Mitochondrial_Disorders': [0.0, 1.0, 1.0, 1.0, 1.0], 'Age': [0.76, 20.0, 20.0, 16.0, 1.0], 'Gender': [0.0, 1.0, 1.0, 0.0, 0.0]}\n", "Saved clinical data to ../../output/preprocess/Mitochondrial_Disorders/clinical_data/GSE42986.csv\n", "Shape of linked data: (53, 19639)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (46, 19639)\n", "For the feature 'Mitochondrial_Disorders', the least common label is '1.0' with 21 occurrences. This represents 45.65% of the dataset.\n", "The distribution of the feature 'Mitochondrial_Disorders' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 1.0\n", " 50% (Median): 5.0\n", " 75%: 19.0\n", "Min: 0.2\n", "Max: 72.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 16 occurrences. This represents 34.78% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved processed linked data to ../../output/preprocess/Mitochondrial_Disorders/GSE42986.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# (This was already done in step 6, but we'll keep this to ensure the correct workflow)\n", "print(f\"Shape of gene data after normalization: {gene_data.shape}\")\n", "\n", "# 2. Extract clinical data from the matrix 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", "# Print out the sample characteristics to verify available rows\n", "characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(\"Sample characteristics dictionary:\")\n", "print(characteristics_dict)\n", "\n", "# Define conversion functions for the clinical features based on the actual data\n", "# Reusing the correct conversion functions from step 2\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert respiratory chain complex deficiency into binary (0 = No deficiency, 1 = Has deficiency)\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # No deficiency cases\n", " if \"No Respiratory Chain Complex Deficiency\" in value:\n", " return 0\n", " # All other cases with respiratory chain complex deficiency\n", " elif \"Complex\" in value or \"Complexes\" in value or \"mtDNA depletion\" in value:\n", " return 1\n", " # If we can't determine\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age to continuous value (float)\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if value.lower() == \"not obtained\":\n", " return None\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender to binary (0 = Female, 1 = Male)\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if value.upper() == \"F\":\n", " return 0\n", " elif value.upper() == \"M\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# Create the clinical dataframe using the identified rows from step 2\n", "try:\n", " clinical_df = geo_select_clinical_features(\n", " clinical_data,\n", " trait=trait, # Using the predefined trait variable\n", " trait_row=1, # Row for respiratory chain complex deficiency\n", " convert_trait=convert_trait,\n", " gender_row=2, # Gender information\n", " convert_gender=convert_gender,\n", " age_row=3, # Age information\n", " convert_age=convert_age\n", " )\n", " \n", " print(\"Clinical data preview:\")\n", " print(preview_df(clinical_df.T)) # Transpose for better viewing\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\"Saved clinical data to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data)\n", " print(f\"Shape of linked data: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values in the linked data\n", " linked_data_cleaned = handle_missing_values(linked_data, trait)\n", " print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", " \n", " # 5. Check if the trait and demographic features are biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", " \n", " # 6. Validate the dataset and save cohort information\n", " note = \"Dataset contains gene expression data from human samples with mitochondrial respiratory chain disease. The trait variable represents respiratory chain complex deficiency (0=No deficiency, 1=Has deficiency).\"\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=True,\n", " is_biased=is_trait_biased,\n", " df=unbiased_linked_data,\n", " note=note\n", " )\n", " \n", " # 7. 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", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", " else:\n", " print(\"Dataset validation failed. Final linked data not saved.\")\n", " \n", "except Exception as e:\n", " print(f\"Error in processing clinical data: {e}\")\n", " # If we failed to extract clinical data, update the cohort info\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=False,\n", " is_biased=None,\n", " df=pd.DataFrame(),\n", " note=\"Failed to extract clinical data. Gene expression data is available but clinical feature extraction failed.\"\n", " )\n", " print(\"Dataset validation failed due to missing or corrupted clinical data. Only gene data saved.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }