{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "d7f1fba8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:24.640787Z", "iopub.status.busy": "2025-03-25T06:33:24.640564Z", "iopub.status.idle": "2025-03-25T06:33:24.804364Z", "shell.execute_reply": "2025-03-25T06:33:24.803941Z" } }, "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 = \"GSE143924\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Arrhythmia\"\n", "in_cohort_dir = \"../../input/GEO/Arrhythmia/GSE143924\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Arrhythmia/GSE143924.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Arrhythmia/gene_data/GSE143924.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Arrhythmia/clinical_data/GSE143924.csv\"\n", "json_path = \"../../output/preprocess/Arrhythmia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bfc68f17", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "30a6115e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:24.805807Z", "iopub.status.busy": "2025-03-25T06:33:24.805670Z", "iopub.status.idle": "2025-03-25T06:33:24.857583Z", "shell.execute_reply": "2025-03-25T06:33:24.857210Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptome analysis from human epicardial adipose tissue biopsies analyzed according to postoperative atrial fibrillation occurrence after cardiac surgery\"\n", "!Series_summary\t\"Introduction: Post-operative atrial fibrillation (POAF) is a frequent complication after cardiac surgery, but its pathophysiology remains incompletely understood. Considering that epicardial adipose tissue (EAT) is in close vicinity with the atrial myocardium, we hypothesized that a specific pre-operative EAT phenotype would be associated to POAF onset following surgery. Methods: Patients undergoing cardiac surgery prospectively enrolled in the POMI-AF cohort between February 2016 and June 2017 were studied. EAT samples were collected at the beginning of surgery. Whole-tissue gene expression patterns and the stromal and vascular fraction (SVF) cellular composition were explored. Patients were followed after surgery by continuous ECG to detect POAF onset. Results: Among the 60 patients included in the cohort, 15 POAF and 15 non-POAF patients were matched based on pre-operative characteristics. Gene set enrichment analysis of transcriptomic data from pre-operative EAT samples revealed 40 enriched biological processes in POAF vs non-POAF patients. Most of these processes were related to cellular immune response. Leukocytes (63±15% of total cells), and more specifically lymphocytes (56±13% of total CD45+ cells), represented the major cell subset in the preoperative EAT SVF, with no quantitative differences between POAF and SR patients (76 [52; 84]% vs 56 [50; 64]%, p=0.22). However, POAF patients presented a significantly higher cytotoxic CD8+/helper CD4+ T lymphocyte ratio than SR patients (respectively, 0.69[0.55; 1.19] vs 0.50 [0.31; 0.54], p=0.03) suggesting a cytotoxic shift prior to surgery. Conclusion: Epicardial fat from patients who develop POAF displays a specific pre-operative transcriptome signature characteristic of cellular immune response and cytotoxic lymphocyte enrichment.\"\n", "!Series_overall_design\t\"30 matched samples analyzed (15 POAF vs 15 SR patients)\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: epicardial adipose tissue'], 1: ['patient diagnosis: sinus rhythm after surgery', 'patient diagnosis: postoperative atrial fibrillation after surgery (POAF)']}\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": "63b2d557", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "42941db0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:24.858637Z", "iopub.status.busy": "2025-03-25T06:33:24.858533Z", "iopub.status.idle": "2025-03-25T06:33:24.863389Z", "shell.execute_reply": "2025-03-25T06:33:24.862978Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data file not found at ../../input/GEO/Arrhythmia/GSE143924/clinical_data.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series title and summary, this dataset appears to contain transcriptome analysis\n", "# which typically includes gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Arrhythmia/POAF), we can see it's available in row 1 of the sample characteristics\n", "trait_row = 1\n", "\n", "# For age and gender, they don't appear to be explicitly mentioned in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary format (0 for sinus rhythm, 1 for POAF)\"\"\"\n", " if isinstance(value, str):\n", " if \"sinus rhythm\" in value.lower():\n", " return 0\n", " elif \"postoperative atrial fibrillation\" in value.lower() or \"poaf\" in value.lower():\n", " return 1\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous format\"\"\"\n", " # Since age data is not available, this function is just a placeholder\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary format (0 for female, 1 for male)\"\"\"\n", " # Since gender data is not available, this function is just a placeholder\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", "# Only proceed if trait_row is not None\n", "if trait_row is not None:\n", " # Load the clinical data\n", " clinical_data_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_data_file):\n", " clinical_data = pd.read_csv(clinical_data_file)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " else:\n", " print(f\"Clinical data file not found at {clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "06ee4598", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "b9008776", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:24.864569Z", "iopub.status.busy": "2025-03-25T06:33:24.864468Z", "iopub.status.idle": "2025-03-25T06:33:24.913883Z", "shell.execute_reply": "2025-03-25T06:33:24.913513Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Arrhythmia/GSE143924/GSE143924_series_matrix.txt.gz\n", "Gene data shape: (8596, 30)\n", "First 20 gene/probe identifiers:\n", "Index(['A2M-AS1', 'AACS', 'AADAC', 'AADACL2', 'AADACP1', 'AAK1', 'AARD',\n", " 'AASS', 'ABCA1', 'ABCA10', 'ABCA11P', 'ABCA3', 'ABCA5', 'ABCA9-AS1',\n", " 'ABCB1', 'ABCB11', 'ABCB4', 'ABCB7', 'ABCC3', 'ABCC6'],\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": "b2e16ad0", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "b79f9bbf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:24.915015Z", "iopub.status.busy": "2025-03-25T06:33:24.914900Z", "iopub.status.idle": "2025-03-25T06:33:24.916781Z", "shell.execute_reply": "2025-03-25T06:33:24.916456Z" } }, "outputs": [], "source": [ "# These identifiers appear to be standard human gene symbols.\n", "# Examples like A2M-AS1, AACS, AADAC, etc. are recognized gene symbols\n", "# rather than probe identifiers that would need mapping.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "335e5d7b", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "00835232", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:33:24.917813Z", "iopub.status.busy": "2025-03-25T06:33:24.917708Z", "iopub.status.idle": "2025-03-25T06:33:27.168849Z", "shell.execute_reply": "2025-03-25T06:33:27.168319Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (8596, 30)\n", "Gene data shape after normalization: (7873, 30)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Arrhythmia/gene_data/GSE143924.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original clinical data preview:\n", " !Sample_geo_accession GSM4276706 \\\n", "0 !Sample_characteristics_ch1 tissue: epicardial adipose tissue \n", "1 !Sample_characteristics_ch1 patient diagnosis: sinus rhythm after surgery \n", "\n", " GSM4276707 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: sinus rhythm after surgery \n", "\n", " GSM4276708 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: sinus rhythm after surgery \n", "\n", " GSM4276709 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: sinus rhythm after surgery \n", "\n", " GSM4276710 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: sinus rhythm after surgery \n", "\n", " GSM4276711 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: sinus rhythm after surgery \n", "\n", " GSM4276712 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: sinus rhythm after surgery \n", "\n", " GSM4276713 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: sinus rhythm after surgery \n", "\n", " GSM4276714 ... \\\n", "0 tissue: epicardial adipose tissue ... \n", "1 patient diagnosis: sinus rhythm after surgery ... \n", "\n", " GSM4276726 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", " GSM4276727 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", " GSM4276728 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", " GSM4276729 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", " GSM4276730 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", " GSM4276731 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", " GSM4276732 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", " GSM4276733 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", " GSM4276734 \\\n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", " GSM4276735 \n", "0 tissue: epicardial adipose tissue \n", "1 patient diagnosis: postoperative atrial fibril... \n", "\n", "[2 rows x 31 columns]\n", "Selected clinical data shape: (1, 30)\n", "Clinical data preview:\n", " GSM4276706 GSM4276707 GSM4276708 GSM4276709 GSM4276710 \\\n", "Arrhythmia 0.0 0.0 0.0 0.0 0.0 \n", "\n", " GSM4276711 GSM4276712 GSM4276713 GSM4276714 GSM4276715 ... \\\n", "Arrhythmia 0.0 0.0 0.0 0.0 0.0 ... \n", "\n", " GSM4276726 GSM4276727 GSM4276728 GSM4276729 GSM4276730 \\\n", "Arrhythmia 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM4276731 GSM4276732 GSM4276733 GSM4276734 GSM4276735 \n", "Arrhythmia 1.0 1.0 1.0 1.0 1.0 \n", "\n", "[1 rows x 30 columns]\n", "Linked data shape before processing: (30, 7874)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Arrhythmia A2M-AS1 AACS AADAC AADACL2\n", "GSM4276706 0.0 508.207839 381.384960 111.908777 69.831635\n", "GSM4276707 0.0 892.370816 1172.689215 20000.000000 78.385174\n", "GSM4276708 0.0 821.254817 264.082320 384.802720 102.435318\n", "GSM4276709 0.0 925.448628 253.827399 209.135691 58.320162\n", "GSM4276710 0.0 489.628264 363.278332 3299.517699 64.239732\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (30, 7874)\n", "For the feature 'Arrhythmia', the least common label is '0.0' with 15 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'Arrhythmia' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (30, 7874)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Arrhythmia/GSE143924.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 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 }