{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "aa3710ea", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:28.058163Z", "iopub.status.busy": "2025-03-25T06:33:28.057996Z", "iopub.status.idle": "2025-03-25T06:33:28.223674Z", "shell.execute_reply": "2025-03-25T06:33:28.223342Z" } }, "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 = \"Arrhythmia\"\n", "cohort = \"GSE182600\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Arrhythmia\"\n", "in_cohort_dir = \"../../input/GEO/Arrhythmia/GSE182600\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Arrhythmia/GSE182600.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Arrhythmia/gene_data/GSE182600.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Arrhythmia/clinical_data/GSE182600.csv\"\n", "json_path = \"../../output/preprocess/Arrhythmia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d91be95a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "3ac9435e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:28.225082Z", "iopub.status.busy": "2025-03-25T06:33:28.224937Z", "iopub.status.idle": "2025-03-25T06:33:28.404435Z", "shell.execute_reply": "2025-03-25T06:33:28.404098Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene Expression of Cardiogenic Shock Patients under Extracorporeal Membrane Oxygenation\"\n", "!Series_summary\t\"Prognosis for cardiogenic shock patients under ECMO was our study goal. Success defined as survived more than 7 days after ECMO installation and failure died or had multiple organ failure in 7 days. Total 34 cases were enrolled, 17 success and 17 failure.\"\n", "!Series_summary\t\"Peripheral blood mononuclear cells collected at ECMO installation 0hr, 2hr and removal were used analyzed.\"\n", "!Series_overall_design\t\"Analysis of the cardiogenic shock patients at extracorporeal membrane oxygenation treatment by genome-wide gene expression. Transcriptomic profiling between successful and failure groups were analyzed.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: Acute myocarditis', 'disease state: Acute myocardial infarction', 'disease state: Dilated cardiomyopathy, DCMP', 'disease state: Congestive heart failure', 'disease state: Dilated cardiomyopathy', 'disease state: Arrhythmia', 'disease state: Aortic dissection'], 1: ['age: 33.4', 'age: 51.2', 'age: 51.9', 'age: 47.8', 'age: 41.5', 'age: 67.3', 'age: 52.8', 'age: 16.1', 'age: 78.9', 'age: 53.2', 'age: 70.9', 'age: 59.9', 'age: 21.9', 'age: 45.2', 'age: 52.4', 'age: 32.3', 'age: 55.8', 'age: 47', 'age: 57.3', 'age: 31.7', 'age: 49.3', 'age: 66.1', 'age: 55.9', 'age: 49.1', 'age: 63', 'age: 21', 'age: 53.6', 'age: 50.1', 'age: 37.4', 'age: 71.5'], 2: ['gender: F', 'gender: M'], 3: ['outcome: Success', 'outcome: Failure', 'outcome: failure'], 4: ['cell type: PBMC'], 5: ['time: 0hr', 'time: 2hr', 'time: Removal']}\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": "79a910d8", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "f6072df9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:28.405615Z", "iopub.status.busy": "2025-03-25T06:33:28.405507Z", "iopub.status.idle": "2025-03-25T06:33:28.418433Z", "shell.execute_reply": "2025-03-25T06:33:28.418149Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{'GSM5532093': [0.0, 33.4, 0.0], 'GSM5532094': [0.0, 51.2, 1.0], 'GSM5532095': [0.0, 51.9, 0.0], 'GSM5532096': [0.0, 47.8, 1.0], 'GSM5532097': [0.0, 41.5, 0.0], 'GSM5532098': [0.0, 67.3, 1.0], 'GSM5532099': [0.0, 52.8, 1.0], 'GSM5532100': [0.0, 16.1, 1.0], 'GSM5532101': [0.0, 78.9, 1.0], 'GSM5532102': [0.0, 53.2, 1.0], 'GSM5532103': [0.0, 70.9, 1.0], 'GSM5532104': [0.0, 59.9, 1.0], 'GSM5532105': [0.0, 21.9, 0.0], 'GSM5532106': [0.0, 45.2, 0.0], 'GSM5532107': [0.0, 52.4, 1.0], 'GSM5532108': [0.0, 32.3, 1.0], 'GSM5532109': [0.0, 52.8, 1.0], 'GSM5532110': [1.0, 55.8, 1.0], 'GSM5532111': [0.0, 47.0, 1.0], 'GSM5532112': [0.0, 55.8, 1.0], 'GSM5532113': [0.0, 57.3, 0.0], 'GSM5532114': [1.0, 31.7, 0.0], 'GSM5532115': [0.0, 49.3, 1.0], 'GSM5532116': [0.0, 66.1, 1.0], 'GSM5532117': [0.0, 55.9, 1.0], 'GSM5532118': [0.0, 49.1, 0.0], 'GSM5532119': [0.0, 63.0, 1.0], 'GSM5532120': [0.0, 21.0, 1.0], 'GSM5532121': [0.0, 53.6, 1.0], 'GSM5532122': [0.0, 50.1, 0.0], 'GSM5532123': [0.0, 37.4, 1.0], 'GSM5532124': [0.0, 71.5, 0.0], 'GSM5532125': [0.0, 56.5, 1.0], 'GSM5532126': [0.0, 33.4, 0.0], 'GSM5532127': [0.0, 51.2, 1.0], 'GSM5532128': [0.0, 51.9, 0.0], 'GSM5532129': [0.0, 47.8, 1.0], 'GSM5532130': [0.0, 41.5, 0.0], 'GSM5532131': [0.0, 67.3, 1.0], 'GSM5532132': [0.0, 52.8, 1.0], 'GSM5532133': [0.0, 78.9, 1.0], 'GSM5532134': [0.0, 53.2, 1.0], 'GSM5532135': [0.0, 70.9, 1.0], 'GSM5532136': [0.0, 59.9, 1.0], 'GSM5532137': [0.0, 21.9, 0.0], 'GSM5532138': [0.0, 45.2, 0.0], 'GSM5532139': [0.0, 52.4, 1.0], 'GSM5532140': [0.0, 32.3, 1.0], 'GSM5532141': [1.0, 55.8, 1.0], 'GSM5532142': [0.0, 47.0, 1.0], 'GSM5532143': [0.0, 55.8, 1.0], 'GSM5532144': [0.0, 57.3, 0.0], 'GSM5532145': [1.0, 31.7, 0.0], 'GSM5532146': [0.0, 49.3, 1.0], 'GSM5532147': [0.0, 66.1, 1.0], 'GSM5532148': [0.0, 55.9, 1.0], 'GSM5532149': [0.0, 49.1, 0.0], 'GSM5532150': [0.0, 63.0, 1.0], 'GSM5532151': [0.0, 21.0, 1.0], 'GSM5532152': [0.0, 53.6, 1.0], 'GSM5532153': [0.0, 50.1, 0.0], 'GSM5532154': [0.0, 37.4, 1.0], 'GSM5532155': [0.0, 71.5, 0.0], 'GSM5532156': [0.0, 56.5, 1.0], 'GSM5532157': [0.0, 33.4, 0.0], 'GSM5532158': [0.0, 51.2, 1.0], 'GSM5532159': [0.0, 51.9, 0.0], 'GSM5532160': [0.0, 47.8, 1.0], 'GSM5532161': [0.0, 52.8, 1.0], 'GSM5532162': [0.0, 53.2, 1.0], 'GSM5532163': [0.0, 21.9, 0.0], 'GSM5532164': [1.0, 55.8, 1.0], 'GSM5532165': [0.0, 47.0, 1.0], 'GSM5532166': [0.0, 49.3, 1.0], 'GSM5532167': [0.0, 66.1, 1.0], 'GSM5532168': [0.0, 53.6, 1.0], 'GSM5532169': [0.0, 50.1, 0.0], 'GSM5532170': [0.0, 56.5, 1.0]}\n", "Clinical features saved to ../../output/preprocess/Arrhythmia/clinical_data/GSE182600.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "from typing import Optional, Callable, Dict, Any, List\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains genome-wide gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking at the sample characteristics dictionary:\n", "\n", "# For trait (Arrhythmia):\n", "# We can see in key 0, there are different disease states including 'Arrhythmia'\n", "trait_row = 0\n", "\n", "# For age:\n", "# We can see in key 1, there are different age values\n", "age_row = 1\n", "\n", "# For gender:\n", "# We can see in key 2, there are gender values (F and M)\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert disease state value to binary (1 if Arrhythmia, 0 otherwise)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if the value contains 'Arrhythmia'\n", " if 'Arrhythmia' in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric value\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'F':\n", " return 0\n", " elif value.upper() == 'M':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering and save metadata\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, extract clinical features\n", "if trait_row is not None:\n", " # Use the clinical_data variable that should be available from a previous step\n", " # Extract clinical features using the geo_select_clinical_features function\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", " 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 clinical features\n", " preview = preview_df(clinical_features)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\n", " \n", " # Ensure the output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical features to CSV\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "cb69c283", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "02550821", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:28.419547Z", "iopub.status.busy": "2025-03-25T06:33:28.419448Z", "iopub.status.idle": "2025-03-25T06:33:28.745690Z", "shell.execute_reply": "2025-03-25T06:33:28.745319Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Arrhythmia/GSE182600/GSE182600_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (29363, 78)\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238',\n", " 'ILMN_1651254', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268',\n", " 'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286',\n", " 'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651309', 'ILMN_1651315'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\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" ] }, { "cell_type": "markdown", "id": "96c9ee00", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "cf320ea5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:28.747011Z", "iopub.status.busy": "2025-03-25T06:33:28.746885Z", "iopub.status.idle": "2025-03-25T06:33:28.748726Z", "shell.execute_reply": "2025-03-25T06:33:28.748454Z" } }, "outputs": [], "source": [ "# These identifiers are from the Illumina microarray platform\n", "# The ILMN_ prefix indicates Illumina probe IDs which need to be mapped to human gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b92ccf96", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "9a37e229", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:28.750057Z", "iopub.status.busy": "2025-03-25T06:33:28.749901Z", "iopub.status.idle": "2025-03-25T06:33:49.483932Z", "shell.execute_reply": "2025-03-25T06:33:49.483270Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'Transcript', 'Species', 'Source', 'Search_Key', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Transcript': ['ILMN_333737', 'ILMN_333646', 'ILMN_333584', 'ILMN_333628', 'ILMN_333719'], 'Species': ['ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls'], 'Source': ['ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls'], 'Search_Key': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'ILMN_Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Source_Reference_ID': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995'], 'Symbol': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Protein_Product': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5270161.0, 4260594.0, 7610424.0, 5260356.0, 2030196.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [12.0, 224.0, 868.0, 873.0, 130.0], 'SEQUENCE': ['CCCATGTGTCCAATTCTGAATATCTTTCCAGCTAAGTGCTTCTGCCCACC', 'GGATTAACTGCTGTGGTGTGTCATACTCGGCTACCTCCTGGTTTGGCGTC', 'GACCACGCCTTGTAATCGTATGACACGCGCTTGACACGACTGAATCCAGC', 'CTGCAATGCCATTAACAACCTTAGCACGGTATTTCCAGTAGCTGGTGAGC', 'CGTGCAGACAGGGATCGTAAGGCGATCCAGCCGGTATACCTTAGTCACAT'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': ['Methanocaldococcus jannaschii spike-in control MJ-500-33 genomic sequence', 'Synthetic construct clone NISTag13 external RNA control sequence', 'Synthetic construct clone TagJ microarray control', 'Methanocaldococcus jannaschii spike-in control MJ-1000-68 genomic sequence', 'Synthetic construct clone AG006.1100 external RNA control sequence'], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995']}\n", "\n", "Analyzing SPOT_ID.1 column for gene symbols:\n", "\n", "Gene data ID prefix: ILMN\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'ID' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'Transcript' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'Species' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'Source' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Checking for columns containing transcript or gene related terms:\n", "Column 'Transcript' may contain gene-related information\n", "Sample values: ['ILMN_333737', 'ILMN_333646', 'ILMN_333584']\n", "Column 'ILMN_Gene' may contain gene-related information\n", "Sample values: ['ERCC-00162', 'ERCC-00071', 'ERCC-00009']\n", "Column 'Entrez_Gene_ID' may contain gene-related information\n", "Sample values: [nan, nan, nan]\n", "Column 'Symbol' may contain gene-related information\n", "Sample values: ['ERCC-00162', 'ERCC-00071', 'ERCC-00009']\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. 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", "# Check for gene information in the SPOT_ID.1 column which appears to contain gene names\n", "print(\"\\nAnalyzing SPOT_ID.1 column for gene symbols:\")\n", "if 'SPOT_ID.1' in gene_annotation.columns:\n", " # Extract a few sample values\n", " sample_values = gene_annotation['SPOT_ID.1'].head(3).tolist()\n", " for i, value in enumerate(sample_values):\n", " print(f\"Sample {i+1} excerpt: {value[:200]}...\") # Print first 200 chars\n", " # Test the extract_human_gene_symbols function on these values\n", " symbols = extract_human_gene_symbols(value)\n", " print(f\" Extracted gene symbols: {symbols}\")\n", "\n", "# Try to find the probe IDs in the gene annotation\n", "gene_data_id_prefix = gene_data.index[0].split('_')[0] # Get prefix of first gene ID\n", "print(f\"\\nGene data ID prefix: {gene_data_id_prefix}\")\n", "\n", "# Look for columns that might match the gene data IDs\n", "for col in gene_annotation.columns:\n", " if gene_annotation[col].astype(str).str.contains(gene_data_id_prefix).any():\n", " print(f\"Column '{col}' contains values matching gene data ID pattern\")\n", "\n", "# Check if there's any column that might contain transcript or gene IDs\n", "print(\"\\nChecking for columns containing transcript or gene related terms:\")\n", "for col in gene_annotation.columns:\n", " if any(term in col.upper() for term in ['GENE', 'TRANSCRIPT', 'SYMBOL', 'NAME', 'DESCRIPTION']):\n", " print(f\"Column '{col}' may contain gene-related information\")\n", " # Show sample values\n", " print(f\"Sample values: {gene_annotation[col].head(3).tolist()}\")\n" ] }, { "cell_type": "markdown", "id": "7666f3a4", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "a3646ee6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:49.485747Z", "iopub.status.busy": "2025-03-25T06:33:49.485618Z", "iopub.status.idle": "2025-03-25T06:33:51.091093Z", "shell.execute_reply": "2025-03-25T06:33:51.090426Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping created with shape: (29377, 2)\n", "Sample of mapping data:\n", " ID Gene\n", "0 ILMN_3166687 ERCC-00162\n", "1 ILMN_3165566 ERCC-00071\n", "2 ILMN_3164811 ERCC-00009\n", "3 ILMN_3165363 ERCC-00053\n", "4 ILMN_3166511 ERCC-00144\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after mapping, shape: (20206, 78)\n", "Sample of first few genes:\n", " GSM5532093 GSM5532094 GSM5532095 GSM5532096 GSM5532097 \\\n", "Gene \n", "A1BG 123.145500 134.323626 100.294706 130.315854 106.890941 \n", "A1CF 442.425800 312.801581 459.891733 648.201284 626.514798 \n", "A26C3 112.721999 93.857780 135.588590 108.663091 106.769778 \n", "A2BP1 428.085657 406.123901 1065.127976 838.139632 437.867618 \n", "A2LD1 694.929347 122.913261 258.573651 693.260663 1139.789587 \n", "\n", " GSM5532098 GSM5532099 GSM5532100 GSM5532101 GSM5532102 ... \\\n", "Gene ... \n", "A1BG 228.719478 149.074810 139.367359 109.260852 152.519107 ... \n", "A1CF 456.501426 369.103327 333.509474 805.121907 333.756113 ... \n", "A26C3 179.172135 115.888185 170.299522 110.064145 138.823068 ... \n", "A2BP1 596.445613 461.428608 452.397602 639.169062 433.651718 ... \n", "A2LD1 796.842538 408.943781 941.280859 1386.872687 416.602005 ... \n", "\n", " GSM5532161 GSM5532162 GSM5532163 GSM5532164 GSM5532165 GSM5532166 \\\n", "Gene \n", "A1BG 117.791486 149.446051 112.994052 153.336376 143.952088 139.646931 \n", "A1CF 307.703312 349.272272 290.645402 305.882066 289.283176 275.041758 \n", "A26C3 117.353917 224.162991 267.033750 387.783190 640.755764 107.929602 \n", "A2BP1 793.561457 517.056382 393.320423 569.086339 456.026782 408.552570 \n", "A2LD1 562.403750 198.910772 477.380383 254.655704 568.428268 456.311147 \n", "\n", " GSM5532167 GSM5532168 GSM5532169 GSM5532170 \n", "Gene \n", "A1BG 143.792296 116.989906 180.882782 183.258185 \n", "A1CF 295.336149 281.371467 293.977954 330.213920 \n", "A26C3 160.200142 156.934820 117.933314 133.436339 \n", "A2BP1 385.614119 448.595827 440.246539 364.734564 \n", "A2LD1 711.873099 466.636213 484.239574 471.306518 \n", "\n", "[5 rows x 78 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to: ../../output/preprocess/Arrhythmia/gene_data/GSE182600.csv\n" ] } ], "source": [ "# 1. Identify the mapping between probe IDs (ID) and gene symbols (Symbol)\n", "prob_col = 'ID' # The column with Illumina probe IDs\n", "gene_col = 'Symbol' # The column with gene symbols\n", "\n", "# 2. Get gene mapping dataframe with the two columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# Print some basic information about the mapping\n", "print(f\"Gene mapping created with shape: {mapping_df.shape}\")\n", "print(\"Sample of mapping data:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Print information about the mapped gene expression data\n", "print(f\"\\nGene expression data after mapping, shape: {gene_data.shape}\")\n", "print(\"Sample of first few genes:\")\n", "print(gene_data.head())\n", "\n", "# Save the gene expression data to file\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": "db785b91", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "45017ae9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:51.092957Z", "iopub.status.busy": "2025-03-25T06:33:51.092827Z", "iopub.status.idle": "2025-03-25T06:34:03.442365Z", "shell.execute_reply": "2025-03-25T06:34:03.441683Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (20206, 78)\n", "Gene data shape after normalization: (19445, 78)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Arrhythmia/gene_data/GSE182600.csv\n", "Original clinical data preview:\n", " !Sample_geo_accession GSM5532093 \\\n", "0 !Sample_characteristics_ch1 disease state: Acute myocarditis \n", "1 !Sample_characteristics_ch1 age: 33.4 \n", "2 !Sample_characteristics_ch1 gender: F \n", "3 !Sample_characteristics_ch1 outcome: Success \n", "4 !Sample_characteristics_ch1 cell type: PBMC \n", "\n", " GSM5532094 GSM5532095 \\\n", "0 disease state: Acute myocarditis disease state: Acute myocarditis \n", "1 age: 51.2 age: 51.9 \n", "2 gender: M gender: F \n", "3 outcome: Success outcome: Failure \n", "4 cell type: PBMC cell type: PBMC \n", "\n", " GSM5532096 \\\n", "0 disease state: Acute myocardial infarction \n", "1 age: 47.8 \n", "2 gender: M \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", " GSM5532097 \\\n", "0 disease state: Acute myocarditis \n", "1 age: 41.5 \n", "2 gender: F \n", "3 outcome: Failure \n", "4 cell type: PBMC \n", "\n", " GSM5532098 \\\n", "0 disease state: Acute myocardial infarction \n", "1 age: 67.3 \n", "2 gender: M \n", "3 outcome: Failure \n", "4 cell type: PBMC \n", "\n", " GSM5532099 \\\n", "0 disease state: Acute myocardial infarction \n", "1 age: 52.8 \n", "2 gender: M \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", " GSM5532100 \\\n", "0 disease state: Dilated cardiomyopathy, DCMP \n", "1 age: 16.1 \n", "2 gender: M \n", "3 outcome: Failure \n", "4 cell type: PBMC \n", "\n", " GSM5532101 ... \\\n", "0 disease state: Acute myocardial infarction ... \n", "1 age: 78.9 ... \n", "2 gender: M ... \n", "3 outcome: Failure ... \n", "4 cell type: PBMC ... \n", "\n", " GSM5532161 \\\n", "0 disease state: Acute myocardial infarction \n", "1 age: 52.8 \n", "2 gender: M \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", " GSM5532162 \\\n", "0 disease state: Acute myocardial infarction \n", "1 age: 53.2 \n", "2 gender: M \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", " GSM5532163 GSM5532164 \\\n", "0 disease state: Acute myocarditis disease state: Arrhythmia \n", "1 age: 21.9 age: 55.8 \n", "2 gender: F gender: M \n", "3 outcome: Success outcome: Success \n", "4 cell type: PBMC cell type: PBMC \n", "\n", " GSM5532165 \\\n", "0 disease state: Dilated cardiomyopathy \n", "1 age: 47 \n", "2 gender: M \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", " GSM5532166 \\\n", "0 disease state: Acute myocardial infarction \n", "1 age: 49.3 \n", "2 gender: M \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", " GSM5532167 \\\n", "0 disease state: Congestive heart failure \n", "1 age: 66.1 \n", "2 gender: M \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", " GSM5532168 \\\n", "0 disease state: Acute myocardial infarction \n", "1 age: 53.6 \n", "2 gender: M \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", " GSM5532169 \\\n", "0 disease state: Acute myocardial infarction \n", "1 age: 50.1 \n", "2 gender: F \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", " GSM5532170 \n", "0 disease state: Congestive heart failure \n", "1 age: 56.5 \n", "2 gender: M \n", "3 outcome: Success \n", "4 cell type: PBMC \n", "\n", "[5 rows x 79 columns]\n", "Selected clinical data shape: (3, 78)\n", "Clinical data preview:\n", " GSM5532093 GSM5532094 GSM5532095 GSM5532096 GSM5532097 \\\n", "Arrhythmia 0.0 0.0 0.0 0.0 0.0 \n", "Age 33.4 51.2 51.9 47.8 41.5 \n", "Gender 0.0 1.0 0.0 1.0 0.0 \n", "\n", " GSM5532098 GSM5532099 GSM5532100 GSM5532101 GSM5532102 ... \\\n", "Arrhythmia 0.0 0.0 0.0 0.0 0.0 ... \n", "Age 67.3 52.8 16.1 78.9 53.2 ... \n", "Gender 1.0 1.0 1.0 1.0 1.0 ... \n", "\n", " GSM5532161 GSM5532162 GSM5532163 GSM5532164 GSM5532165 \\\n", "Arrhythmia 0.0 0.0 0.0 1.0 0.0 \n", "Age 52.8 53.2 21.9 55.8 47.0 \n", "Gender 1.0 1.0 0.0 1.0 1.0 \n", "\n", " GSM5532166 GSM5532167 GSM5532168 GSM5532169 GSM5532170 \n", "Arrhythmia 0.0 0.0 0.0 0.0 0.0 \n", "Age 49.3 66.1 53.6 50.1 56.5 \n", "Gender 1.0 1.0 1.0 0.0 1.0 \n", "\n", "[3 rows x 78 columns]\n", "Linked data shape before processing: (78, 19448)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Arrhythmia Age Gender A1BG A1BG-AS1\n", "GSM5532093 0.0 33.4 0.0 123.145500 1284.286536\n", "GSM5532094 0.0 51.2 1.0 134.323626 2123.843378\n", "GSM5532095 0.0 51.9 0.0 100.294706 1088.857429\n", "GSM5532096 0.0 47.8 1.0 130.315854 1074.517347\n", "GSM5532097 0.0 41.5 0.0 106.890941 1070.809003\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (78, 19448)\n", "For the feature 'Arrhythmia', the least common label is '1.0' with 5 occurrences. This represents 6.41% of the dataset.\n", "The distribution of the feature 'Arrhythmia' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 47.0\n", " 50% (Median): 52.15\n", " 75%: 56.35\n", "Min: 16.1\n", "Max: 78.9\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 24 occurrences. This represents 30.77% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (78, 19448)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Arrhythmia/GSE182600.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# Use normalize_gene_symbols_in_index to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data to file\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 expression data saved to {out_gene_data_file}\")\n", "\n", "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\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", "# Get preview of clinical data to understand its structure\n", "print(\"Original clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# 2. If we have trait data available, proceed with linking\n", "if trait_row is not None:\n", " # Extract clinical features using the original clinical data\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", " print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(selected_clinical_df.head())\n", "\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before processing: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, 5 columns):\")\n", " print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n", "\n", " # 3. Handle missing values\n", " try:\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " linked_data = pd.DataFrame() # Create empty dataframe if error occurs\n", "\n", " # 4. Check for bias in features\n", " if not linked_data.empty and linked_data.shape[0] > 0:\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", " else:\n", " is_biased = True\n", " print(\"Cannot check for bias as dataframe is empty or has no rows after missing value handling\")\n", "\n", " # 5. Validate and save cohort information\n", " note = \"\"\n", " if linked_data.empty or linked_data.shape[0] == 0:\n", " note = \"Dataset contains gene expression data related to liver fibrosis progression, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n", " else:\n", " note = \"Dataset contains gene expression data for liver fibrosis progression, which is relevant to liver cirrhosis research.\"\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=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", "\n", " # 6. Save the linked data if 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(\"Dataset is not usable for analysis. No linked data file saved.\")\n", "else:\n", " # If no trait data available, validate with trait_available=False\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=True, # Set to True since we can't use data without trait\n", " df=pd.DataFrame(), # Empty DataFrame\n", " note=\"Dataset contains gene expression data but lacks proper clinical trait information for liver cirrhosis analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for liver cirrhosis analysis due to lack of clinical trait data. No linked data file 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 }