{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "508dd867", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:36:54.299522Z", "iopub.status.busy": "2025-03-25T06:36:54.299300Z", "iopub.status.idle": "2025-03-25T06:36:54.463362Z", "shell.execute_reply": "2025-03-25T06:36:54.462972Z" } }, "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 = \"GSE55231\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Arrhythmia\"\n", "in_cohort_dir = \"../../input/GEO/Arrhythmia/GSE55231\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Arrhythmia/GSE55231.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Arrhythmia/gene_data/GSE55231.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Arrhythmia/clinical_data/GSE55231.csv\"\n", "json_path = \"../../output/preprocess/Arrhythmia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "c649f00a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "7ea79f83", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:36:54.464636Z", "iopub.status.busy": "2025-03-25T06:36:54.464494Z", "iopub.status.idle": "2025-03-25T06:36:54.809029Z", "shell.execute_reply": "2025-03-25T06:36:54.808605Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Genome-wide identification of expression quantitative trait loci (eQTLs) in human heart: gene expression\"\n", "!Series_summary\t\"In recent years genome-wide association studies (GWAS) have uncovered numerous chromosomal loci associated with various electrocardiographic traits and cardiac arrhythmia predisposition. A considerable fraction of these loci lie within inter-genic regions. Trait-associated SNPs located in putative regulatory regions likely exert their effect by modulating gene expression. Hence, the key to unraveling the molecular mechanisms underlying cardiac traits is to interrogate variants for association with differential transcript abundance by expression quantitative trait locus (eQTL) analysis. In this study we conducted an eQTL analysis of human heart. To this end, left ventricular mycardium samples from non-diseased human donor hearts were hybridized to Illumina HumanOmniExpress BeadChips for genotyping (n = 129) and Illumina Human HT12 Version 4 BeadChips (n = 129) for transcription profiling.\"\n", "!Series_overall_design\t\"To assess the gene expression levels of 129 human donor hearts from the study, genome-wide transcription profiling was carried out using Illumina Human HT12 Version 4 Beadchips interrogating over 47,000 unique transcripts (total of 47323 probes including controls).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: male', 'gender: female'], 1: ['tissue: left ventricular myocardium'], 2: ['age: 31', 'age: 54', 'age: 32', 'age: 41', 'age: 46', 'age: 21', 'age: 44', 'age: 75', 'age: 59', 'age: 34', 'age: 29', 'age: 15', 'age: 52', 'age: 36', 'age: 53', 'age: 26', 'age: 60', 'age: 39', 'age: 20', 'age: 51', 'age: 19', 'age: 14', 'age: 40', 'age: 45', 'age: 42', 'age: 57', 'age: 56', 'age: 72', 'age: 37', 'age: 63'], 3: ['center: 3', 'center: 1', 'center: 2', 'center: 4']}\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": "8c19e59e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "51bfe7a0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:36:54.810258Z", "iopub.status.busy": "2025-03-25T06:36:54.810136Z", "iopub.status.idle": "2025-03-25T06:36:54.818253Z", "shell.execute_reply": "2025-03-25T06:36:54.817798Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any, List\n", "import numpy as np\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on background information, this is a human heart gene expression study using Illumina HT12 BeadChips\n", "is_gene_available = True # This dataset contains gene expression data\n", "\n", "# 2.1 Data Availability\n", "# Trait (Arrhythmia)\n", "# There is no explicit arrhythmia data in the sample characteristics\n", "# This is a normal heart study with no disease information in the metadata\n", "trait_row = None # Arrhythmia data is not available\n", "\n", "# Age\n", "age_row = 2 # Age information is available at index 2\n", "\n", "# Gender\n", "gender_row = 0 # Gender information is available at index 0\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert arrhythmia status to binary values.\n", " 0 = no arrhythmia, 1 = arrhythmia\n", " Since we don't have trait data, this function is defined but won't be used.\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " # Define conversion logic\n", " if value in ['yes', 'arrhythmia', 'present', 'positive', 'true', '1']:\n", " return 1\n", " elif value in ['no', 'none', 'absent', 'negative', 'false', '0']:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " Convert age to continuous values (float).\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to convert to float\n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert gender to binary values.\n", " 0 = female, 1 = male\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " # Define conversion logic\n", " if value in ['male', 'm', '1']:\n", " return 1\n", " elif value in ['female', 'f', '0']:\n", " return 0\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is not available, so is_trait_available is False\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=(trait_row is not None)\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Since trait_row is None, we skip this step as instructed\n" ] }, { "cell_type": "markdown", "id": "b526afa3", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "2e60aff8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:36:54.819762Z", "iopub.status.busy": "2025-03-25T06:36:54.819656Z", "iopub.status.idle": "2025-03-25T06:36:55.410257Z", "shell.execute_reply": "2025-03-25T06:36:55.409690Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Arrhythmia/GSE55231/GSE55231_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (47323, 129)\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. 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": "c7fda9b3", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "22655ba2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:36:55.412097Z", "iopub.status.busy": "2025-03-25T06:36:55.411976Z", "iopub.status.idle": "2025-03-25T06:36:55.413839Z", "shell.execute_reply": "2025-03-25T06:36:55.413583Z" } }, "outputs": [], "source": [ "# The identifiers starting with \"ILMN_\" are Illumina probe IDs, not human gene symbols\n", "# ILMN_ is the prefix used by Illumina microarray platforms\n", "# These probe IDs need to be mapped to human gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "9c94ceaf", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "73d81038", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:36:55.415483Z", "iopub.status.busy": "2025-03-25T06:36:55.415218Z", "iopub.status.idle": "2025-03-25T06:38:06.118342Z", "shell.execute_reply": "2025-03-25T06:38:06.117656Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n", "\n", "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 '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": [ "Column 'Transcript' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'Probe_Id' 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: [nan, nan, nan]\n", "Column 'ILMN_Gene' may contain gene-related information\n", "Sample values: [nan, nan, nan]\n", "Column 'Unigene_ID' may contain gene-related information\n", "Sample values: [nan, nan, nan]\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: ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low']\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": "f5f4197c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5f9b26df", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:38:06.119903Z", "iopub.status.busy": "2025-03-25T06:38:06.119768Z", "iopub.status.idle": "2025-03-25T06:38:08.798947Z", "shell.execute_reply": "2025-03-25T06:38:08.798299Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using ID for probe IDs and Symbol for gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping shape: (44837, 2)\n", "Gene mapping sample:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "Unique probes in gene data: 47323\n", "Unique probes in mapping: 44837\n", "Percentage of probes with mapping: 93.09%\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape (after mapping): (21464, 129)\n", "First few gene symbols after mapping:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n", " 'A4GALT', 'A4GNT'],\n", " dtype='object', name='Gene')\n", "\n", "Gene data preview:\n", "{'GSM1332057': [10.127264694, 14.379807187, 15.035030803000001], 'GSM1332058': [9.944254334, 14.493606312, 14.046573366], 'GSM1332059': [10.142984839, 14.650354162, 14.734314932], 'GSM1332060': [10.091085048, 15.670301627, 14.974311387], 'GSM1332061': [10.265431286999998, 14.149712113, 15.11576243], 'GSM1332062': [10.542400339, 14.603533795, 14.706047456], 'GSM1332063': [9.877080485, 15.060291367000001, 14.514800183999998], 'GSM1332064': [9.966614693, 15.20830677, 14.662965185000001], 'GSM1332065': [9.924015967999999, 14.811890086, 13.821568969000001], 'GSM1332066': [9.13442078, 14.365565483000001, 14.005469864], 'GSM1332067': [9.995247309, 14.518232182, 14.380888581], 'GSM1332068': [10.199034656, 14.724974837, 15.108685398], 'GSM1332069': [10.034946433, 14.806646158, 14.722582978], 'GSM1332070': [9.883628951999999, 15.635986495000001, 14.368809515999999], 'GSM1332071': [10.102539035, 14.406270441, 14.696946574], 'GSM1332072': [9.952748701, 14.457314867000001, 14.423134745999999], 'GSM1332073': [10.111630009999999, 13.989257460000001, 14.367041406999999], 'GSM1332074': [10.587479187, 14.641765244999998, 14.542436783], 'GSM1332075': [10.463194277, 14.532059645, 14.084831819000001], 'GSM1332076': [9.51838358, 14.795196192999999, 14.252208798], 'GSM1332077': [10.958864504000001, 14.499181654000001, 14.502940138], 'GSM1332078': [10.2556621, 14.381134602, 14.818505610999999], 'GSM1332079': [9.984257574, 14.820785515, 14.565413738], 'GSM1332080': [9.869104901, 14.716927563999999, 15.197747971], 'GSM1332081': [9.678913058, 13.927643135, 15.07801487], 'GSM1332082': [9.811463432, 15.091657754, 14.565341275000002], 'GSM1332083': [9.777502651, 14.099968688, 14.449633284], 'GSM1332084': [10.037975309, 14.597665375, 14.37200018], 'GSM1332085': [10.165464518, 14.088651259, 14.305926304], 'GSM1332086': [10.319487616, 14.471570475, 15.372049722], 'GSM1332087': [10.697600744999999, 15.242754389, 14.819530325], 'GSM1332088': [10.08542692, 14.505616608, 14.801504797], 'GSM1332089': [9.963795583, 15.411362243, 15.046334554000001], 'GSM1332090': [10.550106051, 14.544344024, 14.48546855], 'GSM1332091': [10.818175321, 14.665506688, 14.002608859], 'GSM1332092': [10.206659826, 14.624904066, 14.822167671999999], 'GSM1332093': [10.058253618999998, 15.033356863000002, 14.365013852], 'GSM1332094': [9.757460892, 15.301154067999999, 15.90636673], 'GSM1332095': [10.176125568, 14.688870432999998, 14.809869318], 'GSM1332096': [10.481063805, 14.808570317000001, 14.847565396], 'GSM1332097': [10.960476266, 14.313212102, 14.700897589], 'GSM1332098': [10.823015688, 14.844922208, 14.158070124], 'GSM1332099': [10.380628002, 14.791061588, 14.601763878], 'GSM1332100': [10.313250752999998, 15.172311019999999, 14.546096038000002], 'GSM1332101': [10.412666245, 14.190487463, 14.556868101], 'GSM1332102': [10.065907137, 14.26762218, 14.295428777000001], 'GSM1332103': [9.809146983, 14.325944076999999, 14.319902207], 'GSM1332104': [9.871323684, 13.909504708, 14.943151626], 'GSM1332105': [9.998748723999999, 14.029577648, 14.280574996999999], 'GSM1332106': [9.704325613, 14.259075208999999, 14.278224851000001], 'GSM1332107': [9.847039094, 13.818767862, 14.633122544999999], 'GSM1332108': [10.403363282, 14.127764236, 14.988636979], 'GSM1332109': [9.934381822999999, 14.437653299, 15.112508218], 'GSM1332110': [9.723797823, 15.045769316, 14.443984164], 'GSM1332111': [10.211540384, 14.683433962999999, 15.37261052], 'GSM1332112': [9.581778464, 14.264200963, 14.342942947000001], 'GSM1332113': [10.604591147, 14.633774321, 15.063130226], 'GSM1332114': [10.366220005999999, 14.947813423, 13.868438458], 'GSM1332115': [10.248847117, 14.336844928, 14.582874699000001], 'GSM1332116': [10.010863434000001, 14.945361089999999, 14.995931051], 'GSM1332117': [10.268877330999999, 14.467576916, 14.996475492], 'GSM1332118': [10.20479214, 14.877430443, 14.074051233], 'GSM1332119': [9.962667097, 14.348933078, 14.76493013], 'GSM1332120': [10.379318755, 13.952510356000001, 15.180963338], 'GSM1332121': [10.463757699999999, 14.195379992, 14.168132594], 'GSM1332122': [10.748937964, 14.375301132, 14.485138494000001], 'GSM1332123': [10.126869813999999, 14.133540847999999, 14.115879889], 'GSM1332124': [9.647295019000001, 14.58505976, 14.142120564999999], 'GSM1332125': [10.406639703, 14.464996154, 14.213702329], 'GSM1332126': [10.869913446, 14.578797286, 15.137643123], 'GSM1332127': [9.928074037999998, 14.709490114000001, 14.479950616], 'GSM1332128': [9.774108623, 14.623629397, 14.109732641999999], 'GSM1332129': [9.706574312, 14.196468019000001, 14.378361770000001], 'GSM1332130': [10.637229766, 14.478178768, 15.004160931000001], 'GSM1332131': [10.265029987, 14.146675083999998, 14.427787708], 'GSM1332132': [10.053308134, 14.774218387, 14.223326223], 'GSM1332133': [10.185413513, 14.880405386, 14.228969425999999], 'GSM1332134': [9.888984833, 14.663766006, 14.432385651], 'GSM1332135': [10.419760396000001, 14.942279512999999, 13.941850416], 'GSM1332136': [9.91007692, 14.250866126, 14.814426969], 'GSM1332137': [10.095963195, 14.583788572, 14.419461659], 'GSM1332138': [10.612773063999999, 14.731521653, 14.627361031], 'GSM1332139': [11.250714188, 14.524812706999999, 14.571929394000001], 'GSM1332140': [9.651509093, 14.279692558, 14.350883727], 'GSM1332141': [10.778212943, 15.215234494, 14.392076527], 'GSM1332142': [9.914858711, 14.402756310000001, 14.759429541], 'GSM1332143': [9.679750388, 14.070329065, 13.962619343], 'GSM1332144': [9.76114752, 14.759770818, 14.834972079], 'GSM1332145': [9.884833937, 15.039632788999999, 14.799857366], 'GSM1332146': [10.230039055999999, 14.311172194000001, 14.334967634], 'GSM1332147': [10.125070028, 14.646494942, 14.572018625], 'GSM1332148': [10.555246666999999, 14.629512600999998, 15.096082914], 'GSM1332149': [10.144232965, 14.43740167, 14.415220899], 'GSM1332150': [10.709716416, 14.53351731, 14.373831145], 'GSM1332151': [9.677098777000001, 14.211986796000001, 14.526612564], 'GSM1332152': [9.936066843999999, 14.535948144, 14.346062245999999], 'GSM1332153': [10.145465679, 14.861712025, 13.879928540000002], 'GSM1332154': [9.98688915, 14.854586102999999, 14.649951516], 'GSM1332155': [10.148636899, 14.367999899, 14.028849642], 'GSM1332156': [10.307413332, 14.641344753999999, 14.225576705], 'GSM1332157': [9.738214281000001, 14.611845124999999, 15.143327531], 'GSM1332158': [9.844725983, 14.654399281, 15.146997304], 'GSM1332159': [10.135206221, 15.232825385, 14.422493369000001], 'GSM1332160': [10.156550785, 14.260022904, 15.066642901000002], 'GSM1332161': [9.690895193, 15.156215003, 14.227922702], 'GSM1332162': [10.642340648000001, 14.630419123, 13.872009566], 'GSM1332163': [9.964140541999999, 14.901493731999999, 14.807874820999999], 'GSM1332164': [11.08895797, 14.392519755999999, 14.352682206999999], 'GSM1332165': [9.753429846, 14.824246983, 14.345465859], 'GSM1332166': [9.980650766, 14.594896058, 14.515440067], 'GSM1332167': [10.215789602000001, 14.546098877999999, 14.688259961], 'GSM1332168': [10.152725861, 14.606455457, 14.257483286], 'GSM1332169': [10.060652425, 14.21952237, 14.638143651], 'GSM1332170': [10.339100676000001, 14.765375099, 14.292685621], 'GSM1332171': [9.706922216, 14.474453223000001, 14.600918475], 'GSM1332172': [10.100633835, 14.280103280999999, 14.041809422], 'GSM1332173': [9.594701849, 14.619230327, 14.229961275], 'GSM1332174': [10.030859272, 14.990655163, 14.911416804], 'GSM1332175': [9.925767649, 14.609424338, 15.454356753999999], 'GSM1332176': [10.087118783, 14.478773616, 14.859944482], 'GSM1332177': [10.291249912, 14.445498341, 14.370627607], 'GSM1332178': [10.373444725, 14.454680876, 14.881046679], 'GSM1332179': [10.502786795, 15.037662306, 14.460084588], 'GSM1332180': [9.988452747, 14.607420338, 14.395832035000002], 'GSM1332181': [9.922856772, 14.489963857, 13.94837004], 'GSM1332182': [10.074722449, 14.583806374, 14.827724393], 'GSM1332183': [10.135450454, 14.22358621, 14.342958214], 'GSM1332184': [10.13841783, 15.169917583, 14.533244412], 'GSM1332185': [10.076128014, 14.681782819, 14.51409585]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/Arrhythmia/gene_data/GSE55231.csv\n" ] } ], "source": [ "# 1. Identify the columns for probe IDs and gene symbols\n", "prob_col = 'ID' # Contains ILMN probe IDs matching gene expression data\n", "gene_col = 'Symbol' # Contains gene symbols for mapping\n", "\n", "print(f\"Using {prob_col} for probe IDs and {gene_col} for gene symbols\")\n", "\n", "# 2. Get a gene mapping dataframe by extracting the two columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "print(\"Gene mapping sample:\")\n", "print(gene_mapping.head())\n", "\n", "# Check for unmappable probes\n", "unique_probes_in_gene_data = len(gene_data.index.unique())\n", "unique_probes_in_mapping = len(gene_mapping['ID'].unique())\n", "print(f\"Unique probes in gene data: {unique_probes_in_gene_data}\")\n", "print(f\"Unique probes in mapping: {unique_probes_in_mapping}\")\n", "print(f\"Percentage of probes with mapping: {(len(set(gene_data.index) & set(gene_mapping['ID'])) / unique_probes_in_gene_data) * 100:.2f}%\")\n", "\n", "# 3. Convert probe-level measurements to gene expression data\n", "gene_expression_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Gene expression data shape (after mapping): {gene_expression_data.shape}\")\n", "print(\"First few gene symbols after mapping:\")\n", "print(gene_expression_data.index[:10])\n", "\n", "# Update gene_data with the mapped gene expression data\n", "gene_data = gene_expression_data\n", "\n", "# Preview the gene data\n", "print(\"\\nGene data preview:\")\n", "print(preview_df(gene_data, n=3))\n", "\n", "# Save the gene data to the output file\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 data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "c95c8dd8", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "6a8eb382", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:38:08.800879Z", "iopub.status.busy": "2025-03-25T06:38:08.800603Z", "iopub.status.idle": "2025-03-25T06:38:10.898942Z", "shell.execute_reply": "2025-03-25T06:38:10.898302Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (21464, 129)\n", "Gene data shape after normalization: (20259, 129)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Arrhythmia/gene_data/GSE55231.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original clinical data preview:\n", " !Sample_geo_accession GSM1332057 \\\n", "0 !Sample_characteristics_ch1 gender: male \n", "1 !Sample_characteristics_ch1 tissue: left ventricular myocardium \n", "2 !Sample_characteristics_ch1 age: 31 \n", "3 !Sample_characteristics_ch1 center: 3 \n", "\n", " GSM1332058 GSM1332059 \\\n", "0 gender: female gender: male \n", "1 tissue: left ventricular myocardium tissue: left ventricular myocardium \n", "2 age: 54 age: 32 \n", "3 center: 1 center: 3 \n", "\n", " GSM1332060 GSM1332061 \\\n", "0 gender: male gender: male \n", "1 tissue: left ventricular myocardium tissue: left ventricular myocardium \n", "2 age: 41 age: 46 \n", "3 center: 1 center: 3 \n", "\n", " GSM1332062 GSM1332063 \\\n", "0 gender: male gender: male \n", "1 tissue: left ventricular myocardium tissue: left ventricular myocardium \n", "2 age: 21 age: 44 \n", "3 center: 2 center: 3 \n", "\n", " GSM1332064 GSM1332065 \\\n", "0 gender: female gender: male \n", "1 tissue: left ventricular myocardium tissue: left ventricular myocardium \n", "2 age: 46 age: 75 \n", "3 center: 3 center: 4 \n", "\n", " ... GSM1332176 \\\n", "0 ... gender: female \n", "1 ... tissue: left ventricular myocardium \n", "2 ... age: 32 \n", "3 ... center: 1 \n", "\n", " GSM1332177 GSM1332178 \\\n", "0 gender: female gender: female \n", "1 tissue: left ventricular myocardium tissue: left ventricular myocardium \n", "2 age: 51 age: 35 \n", "3 center: 3 center: 3 \n", "\n", " GSM1332179 GSM1332180 \\\n", "0 gender: male gender: female \n", "1 tissue: left ventricular myocardium tissue: left ventricular myocardium \n", "2 age: 44 age: 55 \n", "3 center: 1 center: 2 \n", "\n", " GSM1332181 GSM1332182 \\\n", "0 gender: female gender: male \n", "1 tissue: left ventricular myocardium tissue: left ventricular myocardium \n", "2 age: 52 age: 52 \n", "3 center: 3 center: 3 \n", "\n", " GSM1332183 GSM1332184 \\\n", "0 gender: female gender: female \n", "1 tissue: left ventricular myocardium tissue: left ventricular myocardium \n", "2 age: 27 age: 54 \n", "3 center: 1 center: 3 \n", "\n", " GSM1332185 \n", "0 gender: male \n", "1 tissue: left ventricular myocardium \n", "2 age: 50 \n", "3 center: 3 \n", "\n", "[4 rows x 130 columns]\n", "Abnormality detected in the cohort: GSE55231. Preprocessing failed.\n", "Dataset is not usable for liver cirrhosis analysis due to lack of clinical trait data. No linked data file saved.\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 }