{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "147aed01", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:25:56.548956Z", "iopub.status.busy": "2025-03-25T08:25:56.548720Z", "iopub.status.idle": "2025-03-25T08:25:56.716341Z", "shell.execute_reply": "2025-03-25T08:25:56.716010Z" } }, "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 = \"Congestive_heart_failure\"\n", "cohort = \"GSE93101\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Congestive_heart_failure\"\n", "in_cohort_dir = \"../../input/GEO/Congestive_heart_failure/GSE93101\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Congestive_heart_failure/GSE93101.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Congestive_heart_failure/gene_data/GSE93101.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Congestive_heart_failure/clinical_data/GSE93101.csv\"\n", "json_path = \"../../output/preprocess/Congestive_heart_failure/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6f2b768c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "09762be8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:25:56.717676Z", "iopub.status.busy": "2025-03-25T08:25:56.717543Z", "iopub.status.idle": "2025-03-25T08:25:56.804283Z", "shell.execute_reply": "2025-03-25T08:25:56.803993Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Molecular Prognosis 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 were used analyzed.\"\n", "!Series_overall_design\t\"Analysis of the cardiogenic shock patients at extracorporeal membrane oxygenation treatment by genome-wide expression and methylation. Transcriptomic profiling and DNA methylation between successful and failure groups were analyzed.\"\n", "!Series_overall_design\t\"This submission represents the transcriptome data.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['course: Acute myocarditis', 'course: Acute myocardial infarction', 'course: Dilated cardiomyopathy, DCMP', 'course: Congestive heart failure', 'course: Dilated cardiomyopathy', 'course: Arrhythmia', 'course: 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']}\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": "7add2ced", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "f8c921ed", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:25:56.805483Z", "iopub.status.busy": "2025-03-25T08:25:56.805381Z", "iopub.status.idle": "2025-03-25T08:25:56.815153Z", "shell.execute_reply": "2025-03-25T08:25:56.814866Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features:\n", "{'GSM2443799': [0.0, 33.4, 0.0], 'GSM2443800': [0.0, 51.2, 1.0], 'GSM2443801': [0.0, 51.9, 0.0], 'GSM2443802': [0.0, 47.8, 1.0], 'GSM2443803': [0.0, 41.5, 0.0], 'GSM2443804': [0.0, 67.3, 1.0], 'GSM2443805': [0.0, 52.8, 1.0], 'GSM2443806': [0.0, 16.1, 1.0], 'GSM2443807': [0.0, 78.9, 1.0], 'GSM2443808': [0.0, 53.2, 1.0], 'GSM2443809': [0.0, 70.9, 1.0], 'GSM2443810': [0.0, 59.9, 1.0], 'GSM2443811': [0.0, 21.9, 0.0], 'GSM2443812': [1.0, 45.2, 0.0], 'GSM2443813': [0.0, 52.4, 1.0], 'GSM2443814': [0.0, 32.3, 1.0], 'GSM2443815': [0.0, 52.8, 1.0], 'GSM2443816': [0.0, 55.8, 1.0], 'GSM2443817': [0.0, 47.0, 1.0], 'GSM2443818': [0.0, 55.8, 1.0], 'GSM2443819': [0.0, 57.3, 0.0], 'GSM2443820': [0.0, 31.7, 0.0], 'GSM2443821': [0.0, 49.3, 1.0], 'GSM2443822': [1.0, 66.1, 1.0], 'GSM2443823': [0.0, 55.9, 1.0], 'GSM2443824': [0.0, 49.1, 0.0], 'GSM2443825': [0.0, 63.0, 1.0], 'GSM2443826': [0.0, 21.0, 1.0], 'GSM2443827': [0.0, 53.6, 1.0], 'GSM2443828': [0.0, 50.1, 0.0], 'GSM2443829': [0.0, 37.4, 1.0], 'GSM2443830': [0.0, 71.5, 0.0], 'GSM2443831': [1.0, 56.5, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Congestive_heart_failure/clinical_data/GSE93101.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains transcriptome data\n", "# \"This submission represents the transcriptome data.\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "\n", "# Trait: Congestive heart failure\n", "# Looking at the sample characteristics, key 0 contains \"course: Congestive heart failure\"\n", "# This suggests patients have different conditions, and we're interested in those with CHF\n", "trait_row = 0\n", "\n", "# Age: Available in key 1\n", "age_row = 1\n", "\n", "# Gender: Available in key 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 or 1)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " condition = value.split(\":\", 1)[1].strip()\n", " else:\n", " condition = value.strip()\n", " \n", " # Check if the condition is congestive heart failure (case insensitive)\n", " if condition.lower() == \"congestive heart failure\":\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous (float)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " age_str = value.split(\":\", 1)[1].strip()\n", " else:\n", " age_str = value.strip()\n", " \n", " try:\n", " return float(age_str)\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 the value after the colon\n", " if \":\" in value:\n", " gender = value.split(\":\", 1)[1].strip()\n", " else:\n", " gender = value.strip()\n", " \n", " if gender.upper() == \"F\":\n", " return 0\n", " elif gender.upper() == \"M\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info for initial filtering\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction (if trait_row is not None)\n", "if trait_row is not None:\n", " # Extract clinical features\n", " clinical_features_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 extracted clinical features\n", " preview = preview_df(clinical_features_df)\n", " print(\"Preview of clinical features:\")\n", " print(preview)\n", " \n", " # Save clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features_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": "1fac0d62", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "1e627a09", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:25:56.816289Z", "iopub.status.busy": "2025-03-25T08:25:56.816191Z", "iopub.status.idle": "2025-03-25T08:25:56.940057Z", "shell.execute_reply": "2025-03-25T08:25:56.939619Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Congestive_heart_failure/GSE93101/GSE93101_series_matrix.txt.gz\n", "Gene data shape: (29363, 33)\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": "50eb9800", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "97245137", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:25:56.941465Z", "iopub.status.busy": "2025-03-25T08:25:56.941358Z", "iopub.status.idle": "2025-03-25T08:25:56.943231Z", "shell.execute_reply": "2025-03-25T08:25:56.942947Z" } }, "outputs": [], "source": [ "# The identifiers starting with \"ILMN_\" are Illumina probe IDs, not human gene symbols.\n", "# These are specific to Illumina microarray platforms and need to be mapped to standard gene symbols.\n", "# ILMN_ prefix indicates Illumina's proprietary probe identifiers from their microarray platforms.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "49d4be7c", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "9dfc797f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:25:56.944586Z", "iopub.status.busy": "2025-03-25T08:25:56.944487Z", "iopub.status.idle": "2025-03-25T08:26:07.851780Z", "shell.execute_reply": "2025-03-25T08:26:07.851336Z" } }, "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", "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": "57195f28", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "4fd8c11e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:26:07.853300Z", "iopub.status.busy": "2025-03-25T08:26:07.853179Z", "iopub.status.idle": "2025-03-25T08:26:08.030849Z", "shell.execute_reply": "2025-03-25T08:26:08.030477Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene mapping preview:\n", "Gene mapping shape: (29377, 2)\n", "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144']}\n", "\n", "Gene expression data after mapping:\n", "Shape: (20206, 33)\n", "First 5 gene symbols: ['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1']\n", "Number of unique gene symbols: 20206\n", "Common genes found: ['TP53', 'BRCA1', 'EGFR', 'TNF', 'IL6']\n" ] } ], "source": [ "# 1. Based on the preview, we can see that:\n", "# - 'ID' column in the gene annotation contains the same ILMN_ identifiers used in gene expression data\n", "# - 'Symbol' column contains gene symbols we need to map to\n", "\n", "# 2. Get gene mapping dataframe using the function from the library\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "\n", "# Examine the mapping to verify it has the expected format\n", "print(\"\\nGene mapping preview:\")\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "print(preview_df(gene_mapping, n=5))\n", "\n", "# 3. Apply gene mapping to convert probe-level expression to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Preview the resulting gene expression data\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(f\"First 5 gene symbols: {gene_data.index[:5].tolist()}\")\n", "\n", "# Examine number of unique gene symbols\n", "print(f\"Number of unique gene symbols: {len(gene_data.index.unique())}\")\n", "\n", "# Check if standard gene symbols are present by looking for common genes\n", "common_genes = [\"TP53\", \"BRCA1\", \"EGFR\", \"TNF\", \"IL6\"]\n", "found_genes = [gene for gene in common_genes if gene in gene_data.index]\n", "print(f\"Common genes found: {found_genes}\")\n" ] }, { "cell_type": "markdown", "id": "a23bc703", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "24420a29", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:26:08.032641Z", "iopub.status.busy": "2025-03-25T08:26:08.032528Z", "iopub.status.idle": "2025-03-25T08:26:14.377772Z", "shell.execute_reply": "2025-03-25T08:26:14.377224Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (20206, 33)\n", "Gene data shape after normalization: (19445, 33)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Congestive_heart_failure/gene_data/GSE93101.csv\n", "Original clinical data preview:\n", " !Sample_geo_accession GSM2443799 \\\n", "0 !Sample_characteristics_ch1 course: 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", "\n", " GSM2443800 GSM2443801 \\\n", "0 course: Acute myocarditis course: Acute myocarditis \n", "1 age: 51.2 age: 51.9 \n", "2 gender: M gender: F \n", "3 outcome: Success outcome: Failure \n", "\n", " GSM2443802 GSM2443803 \\\n", "0 course: Acute myocardial infarction course: Acute myocarditis \n", "1 age: 47.8 age: 41.5 \n", "2 gender: M gender: F \n", "3 outcome: Success outcome: Failure \n", "\n", " GSM2443804 GSM2443805 \\\n", "0 course: Acute myocardial infarction course: Acute myocardial infarction \n", "1 age: 67.3 age: 52.8 \n", "2 gender: M gender: M \n", "3 outcome: Failure outcome: Success \n", "\n", " GSM2443806 GSM2443807 \\\n", "0 course: Dilated cardiomyopathy, DCMP course: Acute myocardial infarction \n", "1 age: 16.1 age: 78.9 \n", "2 gender: M gender: M \n", "3 outcome: Failure outcome: Failure \n", "\n", " ... GSM2443822 GSM2443823 \\\n", "0 ... course: Congestive heart failure course: Aortic dissection \n", "1 ... age: 66.1 age: 55.9 \n", "2 ... gender: M gender: M \n", "3 ... outcome: Success outcome: Failure \n", "\n", " GSM2443824 GSM2443825 \\\n", "0 course: Dilated cardiomyopathy, DCMP course: Acute myocardial infarction \n", "1 age: 49.1 age: 63 \n", "2 gender: F gender: M \n", "3 outcome: Failure outcome: Failure \n", "\n", " GSM2443826 GSM2443827 \\\n", "0 course: Dilated cardiomyopathy, DCMP course: Acute myocardial infarction \n", "1 age: 21 age: 53.6 \n", "2 gender: M gender: M \n", "3 outcome: Failure outcome: Success \n", "\n", " GSM2443828 GSM2443829 \\\n", "0 course: Acute myocardial infarction course: Acute myocardial infarction \n", "1 age: 50.1 age: 37.4 \n", "2 gender: F gender: M \n", "3 outcome: Success outcome: Failure \n", "\n", " GSM2443830 GSM2443831 \n", "0 course: Acute myocarditis course: Congestive heart failure \n", "1 age: 71.5 age: 56.5 \n", "2 gender: F gender: M \n", "3 outcome: Success outcome: Success \n", "\n", "[4 rows x 34 columns]\n", "Selected clinical data shape: (3, 33)\n", "Clinical data preview:\n", " GSM2443799 GSM2443800 GSM2443801 GSM2443802 \\\n", "Congestive_heart_failure 0.0 0.0 0.0 0.0 \n", "Age 33.4 51.2 51.9 47.8 \n", "Gender 0.0 1.0 0.0 1.0 \n", "\n", " GSM2443803 GSM2443804 GSM2443805 GSM2443806 \\\n", "Congestive_heart_failure 0.0 0.0 0.0 0.0 \n", "Age 41.5 67.3 52.8 16.1 \n", "Gender 0.0 1.0 1.0 1.0 \n", "\n", " GSM2443807 GSM2443808 ... GSM2443822 GSM2443823 \\\n", "Congestive_heart_failure 0.0 0.0 ... 1.0 0.0 \n", "Age 78.9 53.2 ... 66.1 55.9 \n", "Gender 1.0 1.0 ... 1.0 1.0 \n", "\n", " GSM2443824 GSM2443825 GSM2443826 GSM2443827 \\\n", "Congestive_heart_failure 0.0 0.0 0.0 0.0 \n", "Age 49.1 63.0 21.0 53.6 \n", "Gender 0.0 1.0 1.0 1.0 \n", "\n", " GSM2443828 GSM2443829 GSM2443830 GSM2443831 \n", "Congestive_heart_failure 0.0 0.0 0.0 1.0 \n", "Age 50.1 37.4 71.5 56.5 \n", "Gender 0.0 1.0 0.0 1.0 \n", "\n", "[3 rows x 33 columns]\n", "Linked data shape before processing: (33, 19448)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Congestive_heart_failure Age Gender A1BG A1BG-AS1\n", "GSM2443799 0.0 33.4 0.0 129.442547 1330.542639\n", "GSM2443800 0.0 51.2 1.0 142.061233 2177.610030\n", "GSM2443801 0.0 51.9 0.0 103.958331 1130.866630\n", "GSM2443802 0.0 47.8 1.0 137.556161 1116.450458\n", "GSM2443803 0.0 41.5 0.0 111.260768 1112.964973\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (33, 19448)\n", "For the feature 'Congestive_heart_failure', the least common label is '1.0' with 3 occurrences. This represents 9.09% of the dataset.\n", "Quartiles for 'Age':\n", " 25%: 45.2\n", " 50% (Median): 52.4\n", " 75%: 56.5\n", "Min: 16.1\n", "Max: 78.9\n", "For the feature 'Gender', the least common label is '0.0' with 10 occurrences. This represents 30.30% of the dataset.\n", "Dataset is not usable for analysis. 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", " # Check if trait is biased\n", " trait_type = 'binary' if len(linked_data[trait].unique()) <= 2 else 'continuous'\n", " if trait_type == \"binary\":\n", " is_biased = judge_binary_variable_biased(linked_data, trait)\n", " else:\n", " is_biased = judge_continuous_variable_biased(linked_data, trait)\n", " \n", " # Remove biased demographic features\n", " if \"Age\" in linked_data.columns:\n", " age_biased = judge_continuous_variable_biased(linked_data, 'Age')\n", " if age_biased:\n", " linked_data = linked_data.drop(columns='Age')\n", " \n", " if \"Gender\" in linked_data.columns:\n", " gender_biased = judge_binary_variable_biased(linked_data, 'Gender')\n", " if gender_biased:\n", " linked_data = linked_data.drop(columns='Gender')\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 atrial fibrillation after cardiac surgery, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n", " else:\n", " note = \"Dataset contains gene expression data for atrial fibrillation after cardiac surgery, which is relevant to arrhythmia 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 arrhythmia analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for arrhythmia 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 }