{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "4c84ae39", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:17.538360Z", "iopub.status.busy": "2025-03-25T05:52:17.538169Z", "iopub.status.idle": "2025-03-25T05:52:17.696039Z", "shell.execute_reply": "2025-03-25T05:52:17.695660Z" } }, "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 = \"GSE22651\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mitochondrial_Disorders\"\n", "in_cohort_dir = \"../../input/GEO/Mitochondrial_Disorders/GSE22651\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mitochondrial_Disorders/GSE22651.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mitochondrial_Disorders/gene_data/GSE22651.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mitochondrial_Disorders/clinical_data/GSE22651.csv\"\n", "json_path = \"../../output/preprocess/Mitochondrial_Disorders/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "df6d619a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0f965559", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:17.697322Z", "iopub.status.busy": "2025-03-25T05:52:17.697180Z", "iopub.status.idle": "2025-03-25T05:52:17.876570Z", "shell.execute_reply": "2025-03-25T05:52:17.876249Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE22651_family.soft.gz', 'GSE22651_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Mitochondrial_Disorders/GSE22651/GSE22651_family.soft.gz\n", "Matrix file: ../../input/GEO/Mitochondrial_Disorders/GSE22651/GSE22651_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"Friedreich’s Ataxia Induced Pluripotent Stem Cells Recapitulate GAA•TTC Triplet-Repeat Instability\"\n", "!Series_summary\t\"The inherited neurodegenerative disease Friedreich’s ataxia (FRDA) is caused by hyperexpansion of GAA•TTC trinucleotide repeats within the first intron of the FXN gene, encoding the mitochondrial protein frataxin. Long GAA•TTC repeats causes heterochromatin-mediated silencing and loss of frataxin in affected individuals. We report the derivation of induced pluripotent stem cells (iPSCs) from FRDA patient fibroblasts through retroviral transduction of transcription factors. FXN gene repression is maintained in the iPSCs, as are the mRNA and miRNA global expression signatures reflecting the human disease. GAA•TTC repeats uniquely in FXN in the iPSCs exhibit repeat instability similar to patient families, where they expand and/or contract with discrete changes in length between generations. The mismatch repair enzyme Msh2, implicated in repeat instability in other triplet repeat diseases, is highly expressed in the iPSCs, occupies FXN intron 1, and shRNA silencing of Msh2 impedes repeat expansion, providing a possible molecular explanation for repeat expansion in FRDA.\"\n", "!Series_overall_design\t\"65 samples from various number of tissue, primary cell lines undifferenatiated human embryonic stem cell lines, induces pluripotent stem cell lines have been run on Illumina HT12 v3 chips.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: male', 'age: 47 years', 'cell line: Human embryonic stem cell line BG01', 'cell line: Human embryonic stem cell line BG02', 'cell line: Human embryonic stem cell line BG03', 'cell line: Human induced pluripotent stem cell line ES4CL2', 'cell line: Human induced pluripotent stem cell line Gottesfeld_3816.5_1', 'cell line: Human induced pluripotent stem cell line Gottesfeld_3816.5_2', 'cell line: Human induced pluripotent stem cell line Gottesfeld_4078.1A2_1', 'cell line: Human induced pluripotent stem cell line Gottesfeld_4078.1A2_2', 'cell line: Human induced pluripotent stem cell line Gottesfeld_4078.1B3_1', 'cell line: Human induced pluripotent stem cell line Gottesfeld_4078.1B3_2', 'cell line: Human induced pluripotent stem cell line Gottesfeld_8.2A4R_1', 'cell line: Human induced pluripotent stem cell line Gottesfeld_8.2A4R_2', 'cell line: Human embryonic stem cell line H9', 'cell line: Human dermal fibroblast line HDF_A', 'cell line: Human dermal fibroblast line HDF_B', 'cell line: Human embryonic stem cell line HES-2_A', 'cell line: Human embryonic stem cell line HES-2_B', 'cell line: Human induced pluripotent stem cell line hFib2-Ips5_A', 'cell line: Human induced pluripotent stem cell line hFib2-Ips5_B', 'cell type: Human Mesenchymal_Stem_Cells_adipose HMSC-ad', 'cell type: Human Mesenchymal_Stem_Cells_bone_marrow HMSC-bm', 'cell line: Primary cell line (Human foreskin fibroblasts) HS27_A', 'cell line: Primary cell line (Human foreskin fibroblasts) HS27_B', 'cell line: Human embryonic stem cell line HSF6_A', 'cell line: Human embryonic stem cell line HSF6_B', 'cell line: Primary cell line human keratinocytes HumanKeratinocytes_A', 'cell line: Primary cell line human keratinocytes HumanKeratinocytes_B', 'cell line: Human Umbilical Vein Endothelial Cell Line HUVEC-BF4'], 1: ['tissue: Adipose tissue from patient 1', 'gender: female', 'tissue: Adrenal tissue from patient 1', nan, 'tissue: Bladder tissue from patient 1', 'tissue: Lung tissue from Patient 1', 'tissue: Ureter tissue from Patient 1'], 2: [nan, 'tissue: Adipose tissue from patient 2', 'tissue: Adrenal tissue from patient 2', 'tissue: Bladder tissue from patient 2', 'tissue: Lung tissue from Patient 2', 'tissue: Ureter tissue from Patient 2']}\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": "88bc4ce8", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "3fe7dffe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:17.878398Z", "iopub.status.busy": "2025-03-25T05:52:17.878282Z", "iopub.status.idle": "2025-03-25T05:52:18.263949Z", "shell.execute_reply": "2025-03-25T05:52:18.263609Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "{0: [0.0], 1: [0.0], 2: [0.0], 3: [0.0], 4: [0.0], 5: [0.0], 6: [0.0], 7: [0.0], 8: [0.0], 9: [0.0], 10: [0.0], 11: [0.0], 12: [0.0], 13: [0.0], 14: [0.0], 15: [0.0], 16: [0.0], 17: [0.0], 18: [0.0], 19: [0.0], 20: [0.0], 21: [0.0], 22: [0.0], 23: [0.0], 24: [0.0], 25: [0.0], 26: [0.0], 27: [0.0], 28: [0.0], 29: [0.0], 30: [0.0], 31: [0.0], 32: [0.0], 33: [0.0], 34: [0.0], 35: [0.0], 36: [0.0], 37: [0.0], 38: [0.0], 39: [0.0], 40: [0.0], 41: [0.0], 42: [0.0], 43: [0.0], 44: [0.0], 45: [0.0], 46: [0.0], 47: [0.0], 48: [0.0], 49: [0.0], 50: [0.0], 51: [0.0], 52: [0.0], 53: [0.0], 54: [0.0], 55: [0.0], 56: [0.0], 57: [0.0], 58: [0.0], 59: [0.0], 60: [0.0], 61: [0.0], 62: [0.0], 63: [0.0], 64: [0.0], 65: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Mitochondrial_Disorders/clinical_data/GSE22651.csv\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_42065/2160290617.py:93: DtypeWarning: Columns (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65) have mixed types. Specify dtype option on import or set low_memory=False.\n", " clinical_data = pd.read_csv(f\"{in_cohort_dir}/GSE22651_series_matrix.txt.gz\",\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Dict, Any, Optional, Callable, List\n", "\n", "# 1. Determine if gene expression data is available\n", "# This dataset appears to have gene expression data from the Illumina HT12 v3 platform\n", "# The study uses iPSCs and investigates gene expression related to Friedreich's ataxia\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics, identify where the trait (Mitochondrial_Disorders/Friedreich's ataxia) is recorded\n", "# Looking at the cell line descriptions, we can see Friedreich's ataxia patient samples vs controls\n", "trait_row = 0 # Cell line information contains information about FRDA patient samples\n", "\n", "# Age information is available but appears to be constant (47 years)\n", "# Since constant features aren't useful for association studies, we'll consider it unavailable\n", "age_row = None\n", "\n", "# Gender information is available but appears to be mostly male in row 0, with some female samples in row 1\n", "# However, this seems to be mixing different samples, not describing all samples consistently\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert cell line information to binary trait values.\n", " FRDA patient samples are coded as 1, control samples as 0.\n", " \"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Remove 'cell line: ' or 'cell type: ' prefix if present\n", " if isinstance(value, str):\n", " if ': ' in value:\n", " value = value.split(': ', 1)[1]\n", " \n", " # Identify Friedreich's ataxia samples based on the cell line names\n", " if 'Gottesfeld_' in value and any(x in value for x in ['3816.5', '4078.1A2', '4078.1B3']):\n", " return 1 # FRDA patient samples\n", " return 0 # Control samples\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age information to continuous values.\n", " \"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " if isinstance(value, str) and ': ' in value:\n", " value = value.split(': ', 1)[1]\n", " \n", " # Extract numeric age value\n", " if 'years' in value:\n", " try:\n", " return float(value.replace('years', '').strip())\n", " except ValueError:\n", " return None\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender information to binary values.\n", " Female = 0, Male = 1\n", " \"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " if isinstance(value, str) and ': ' in value:\n", " value = value.split(': ', 1)[1].lower()\n", " \n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save metadata - Initial filtering\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", "if trait_row is not None:\n", " # Load the clinical data\n", " clinical_data = pd.read_csv(f\"{in_cohort_dir}/GSE22651_series_matrix.txt.gz\", \n", " compression='gzip', sep='\\t', comment='!', \n", " skiprows=0, header=None)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = 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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical Data Preview:\")\n", " print(preview)\n", " \n", " # Save to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "7875108b", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "a1b17388", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:18.265958Z", "iopub.status.busy": "2025-03-25T05:52:18.265801Z", "iopub.status.idle": "2025-03-25T05:52:18.544843Z", "shell.execute_reply": "2025-03-25T05:52:18.544479Z" } }, "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" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 48786\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\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": "9033df14", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "8075b641", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:18.546611Z", "iopub.status.busy": "2025-03-25T05:52:18.546482Z", "iopub.status.idle": "2025-03-25T05:52:18.548456Z", "shell.execute_reply": "2025-03-25T05:52:18.548148Z" } }, "outputs": [], "source": [ "# The identifiers starting with \"ILMN_\" are Illumina microarray probe IDs \n", "# These are not human gene symbols and will need to be mapped to gene symbols\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "2ad6f2dc", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "c4f8749b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:18.550237Z", "iopub.status.busy": "2025-03-25T05:52:18.550089Z", "iopub.status.idle": "2025-03-25T05:52:25.980342Z", "shell.execute_reply": "2025-03-25T05:52:25.979975Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ILMN_1725881', 'ILMN_1910180', 'ILMN_1804174', 'ILMN_1796063', 'ILMN_1811966'], 'nuID': ['rp13_p1x6D80lNLk3c', 'NEX0oqCV8.er4HVfU4', 'KyqQynMZxJcruyylEU', 'xXl7eXuF7sbPEp.KFI', '9ckqJrioiaej9_ajeQ'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'Unigene', 'RefSeq', 'RefSeq', 'RefSeq'], 'Search_Key': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282', 'ILMN_5006', 'ILMN_38756'], 'Transcript': ['ILMN_44919', 'ILMN_127219', 'ILMN_139282', 'ILMN_5006', 'ILMN_38756'], 'ILMN_Gene': ['LOC23117', 'HS.575038', 'FCGR2B', 'TRIM44', 'LOC653895'], 'Source_Reference_ID': ['XM_933824.1', 'Hs.575038', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'RefSeq_ID': ['XM_933824.1', nan, 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'Unigene_ID': [nan, 'Hs.575038', nan, nan, nan], 'Entrez_Gene_ID': [23117.0, nan, 2213.0, 54765.0, 653895.0], 'GI': [89040007.0, 10437021.0, 88952550.0, 29029528.0, 89033487.0], 'Accession': ['XM_933824.1', 'AK024680', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1'], 'Symbol': ['LOC23117', nan, 'FCGR2B', 'TRIM44', 'LOC653895'], 'Protein_Product': ['XP_938917.1', nan, 'XP_943944.1', 'NP_060053.2', 'XP_941472.1'], 'Array_Address_Id': [1710221.0, 5900364.0, 2480717.0, 1300239.0, 4480719.0], 'Probe_Type': ['I', 'S', 'I', 'S', 'S'], 'Probe_Start': [122.0, 1409.0, 1643.0, 2901.0, 25.0], 'SEQUENCE': ['GGCTCCTCTTTGGGCTCCTACTGGAATTTATCAGCCATCAGTGCATCTCT', 'ACACCTTCAGGAGGGAAGCCCTTATTTCTGGGTTGAACTCCCCTTCCATG', 'TAGGGGCAATAGGCTATACGCTACAGCCTAGGTGTGTAGTAGGCCACACC', 'CCTGCCTGTCTGCCTGTGACCTGTGTACGTATTACAGGCTTTAGGACCAG', 'CTAGCAGGGAGCGGTGAGGGAGAGCGGCTGGATTTCTTGCGGGATCTGCA'], 'Chromosome': ['16', nan, nan, '11', nan], 'Probe_Chr_Orientation': ['-', nan, nan, '+', nan], 'Probe_Coordinates': ['21766363-21766363:21769901-21769949', nan, nan, '35786070-35786119', nan], 'Cytoband': ['16p12.2a', nan, '1q23.3b', '11p13a', '10q11.23b'], 'Definition': ['PREDICTED: Homo sapiens KIAA0220-like protein, transcript variant 11 (LOC23117), mRNA.', 'Homo sapiens cDNA: FLJ21027 fis, clone CAE07110', 'PREDICTED: Homo sapiens Fc fragment of IgG, low affinity IIb, receptor (CD32) (FCGR2B), mRNA.', 'Homo sapiens tripartite motif-containing 44 (TRIM44), mRNA.', 'PREDICTED: Homo sapiens similar to protein geranylgeranyltransferase type I, beta subunit (LOC653895), mRNA.'], 'Ontology_Component': [nan, nan, nan, 'intracellular [goid 5622] [evidence IEA]', nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, 'zinc ion binding [goid 8270] [evidence IEA]; metal ion binding [goid 46872] [evidence IEA]', nan], 'Synonyms': [nan, nan, nan, 'MGC3490; MC7; HSA249128; DIPB', nan], 'Obsolete_Probe_Id': [nan, nan, nan, 'MGC3490; MC7; HSA249128; DIPB', nan], 'GB_ACC': ['XM_933824.1', 'AK024680', 'XM_938851.1', 'NM_017583.3', 'XM_936379.1']}\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": "37f53c51", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "cc2ffba8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:25.982353Z", "iopub.status.busy": "2025-03-25T05:52:25.982191Z", "iopub.status.idle": "2025-03-25T05:52:26.872381Z", "shell.execute_reply": "2025-03-25T05:52:26.872017Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total probe IDs in annotation: 36157\n", "Probes with non-null gene symbols: 36157\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data (after mapping):\n", "Number of genes: 19113\n", "Number of samples: 65\n", "Preview of first few genes:\n", " GSM561902 GSM561903 GSM561904 GSM561905 GSM561906 GSM561907 \\\n", "Gene \n", "A1BG 92.60890 94.52868 95.21268 109.73706 95.10968 109.35627 \n", "A1CF 142.99545 139.53345 139.75102 165.56672 164.79624 157.82081 \n", "A26A1 92.63642 89.08897 90.63681 79.11640 80.38349 86.49739 \n", "A26B1 43.41431 47.92001 43.16347 47.04470 47.18934 47.88204 \n", "A26C1B 51.90683 44.11874 37.29777 42.03285 54.36165 52.47712 \n", "\n", " GSM561908 GSM561909 GSM561910 GSM561911 ... GSM561957 GSM561958 \\\n", "Gene ... \n", "A1BG 110.12251 99.80524 118.76684 110.66915 ... 100.01105 112.85140 \n", "A1CF 156.58730 143.19521 141.03652 148.78001 ... 134.88155 156.66808 \n", "A26A1 97.17016 85.74159 83.81728 77.22961 ... 124.40231 99.92741 \n", "A26B1 41.18475 38.81845 45.67216 42.33515 ... 39.28036 42.28136 \n", "A26C1B 42.67361 47.65977 42.61427 48.11750 ... 113.04590 54.07240 \n", "\n", " GSM561959 GSM561960 GSM561961 GSM561962 GSM561963 GSM561964 \\\n", "Gene \n", "A1BG 123.18717 121.44437 106.36110 102.55130 103.90278 121.97901 \n", "A1CF 157.29936 145.05333 150.38540 179.42628 154.82643 174.87939 \n", "A26A1 94.33304 95.34501 108.43893 107.63442 94.14082 101.64172 \n", "A26B1 41.46817 47.94767 42.43875 39.76659 43.05666 37.96856 \n", "A26C1B 48.02093 46.78205 44.66648 47.80139 46.63743 52.10152 \n", "\n", " GSM561965 GSM561966 \n", "Gene \n", "A1BG 101.27248 106.40507 \n", "A1CF 136.41703 134.52557 \n", "A26A1 93.47603 85.40734 \n", "A26B1 47.50356 40.35231 \n", "A26C1B 41.81384 47.19807 \n", "\n", "[5 rows x 65 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Mitochondrial_Disorders/gene_data/GSE22651.csv\n" ] } ], "source": [ "# 1. Based on the previous outputs, determine which columns to use for mapping\n", "# The 'ID' column in gene_annotation contains Illumina probe IDs (ILMN_*) that match the gene expression data indices\n", "# The 'Symbol' column contains the gene symbols we want to map to\n", "prob_col = 'ID'\n", "gene_col = 'Symbol'\n", "\n", "# 2. Get gene mapping dataframe by extracting the probe ID and gene symbol columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# Check how many probes have gene symbols\n", "print(f\"Total probe IDs in annotation: {len(mapping_df)}\")\n", "print(f\"Probes with non-null gene symbols: {mapping_df['Gene'].notnull().sum()}\")\n", "\n", "# 3. Convert probe-level measurements to gene-level expression data\n", "# Apply the gene mapping to distribute probe values across genes and sum by gene\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Check the resulting gene expression data\n", "print(\"\\nGene expression data (after mapping):\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "print(f\"Number of samples: {gene_data.shape[1]}\")\n", "print(\"Preview of first few genes:\")\n", "print(gene_data.head())\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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "e262b058", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "59e7bb1e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:52:26.874193Z", "iopub.status.busy": "2025-03-25T05:52:26.874071Z", "iopub.status.idle": "2025-03-25T05:52:27.589509Z", "shell.execute_reply": "2025-03-25T05:52:27.589162Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data before normalization: (19113, 65)\n", "Shape of gene data after normalization: (18319, 65)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Mitochondrial_Disorders/gene_data/GSE22651.csv\n", "Loaded clinical data from ../../output/preprocess/Mitochondrial_Disorders/clinical_data/GSE22651.csv\n", "Shape of clinical data: (1, 66)\n", "Error in data linking and validation: Length mismatch: Expected axis has 1 elements, new values have 65 elements\n", "Abnormality detected in the cohort: GSE22651. Preprocessing failed.\n", "A new JSON file was created at: ../../output/preprocess/Mitochondrial_Disorders/cohort_info.json\n", "Dataset validation failed due to processing error. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Apply normalization to standardize gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Shape of gene data before normalization: {gene_data.shape}\")\n", " print(f\"Shape of gene data after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " normalized_gene_data = gene_data\n", " print(\"Using original gene data without normalization.\")\n", "\n", "# 2. Link the clinical and genetic data\n", "try:\n", " # Load the previously saved clinical data\n", " if os.path.exists(out_clinical_data_file):\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data from {out_clinical_data_file}\")\n", " print(f\"Shape of clinical data: {clinical_df.shape}\")\n", " \n", " # Check column mismatch and align indices\n", " if clinical_df.shape[1] != normalized_gene_data.shape[1] + 1: # +1 for index column\n", " print(\"Column count mismatch between clinical and gene data.\")\n", " # Create compatible clinical dataframe with same sample IDs as gene data\n", " print(\"Creating compatible clinical dataframe...\")\n", " # Extract value column which contains the trait information\n", " if clinical_df.shape[1] > 1: # Has both index and data columns\n", " trait_values = [0.0] * normalized_gene_data.shape[1] # Default to all controls\n", " clinical_df = pd.DataFrame({trait: trait_values}, index=normalized_gene_data.columns)\n", " is_trait_available = False # Mark as not available since we're using placeholder data\n", " else:\n", " is_trait_available = False\n", " else:\n", " # Re-extract the clinical data if needed\n", " print(\"Clinical data file not found. Using placeholder data.\")\n", " trait_values = [0.0] * normalized_gene_data.shape[1] # Default to all controls\n", " clinical_df = pd.DataFrame({trait: trait_values}, index=normalized_gene_data.columns)\n", " is_trait_available = False # Mark as not available since we're using placeholder data\n", " \n", " # Ensure indices align between clinical and gene data\n", " clinical_df.index = normalized_gene_data.columns\n", " \n", " # Link the clinical and genetic data\n", " linked_data = pd.concat([clinical_df.T, normalized_gene_data], axis=0)\n", " print(f\"Shape of linked data: {linked_data.shape}\")\n", " \n", " # 3. 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", " # 4. 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", " # 5. Validate the dataset and save cohort information\n", " note = \"This dataset contains gene expression data from cell lines studying Friedreich's ataxia, a mitochondrial disorder. However, the clinical data could not be properly linked with the gene expression data, making it unusable for trait-gene association studies.\"\n", " \n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_trait_biased,\n", " df=unbiased_linked_data,\n", " note=note\n", " )\n", " \n", " # 6. 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 data linking and validation: {e}\")\n", " # Create a minimal DataFrame for error handling\n", " empty_df = pd.DataFrame({trait: []})\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, # Properly mark trait as unavailable\n", " is_biased=True, # Set to True since we can't use the data\n", " df=empty_df,\n", " note=\"Data processing error occurred. The gene expression data is available, but the clinical data could not be properly linked due to a technical error.\"\n", " )\n", " print(\"Dataset validation failed due to processing error. Data not 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 }