{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "74496df3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:34:04.479715Z", "iopub.status.busy": "2025-03-25T06:34:04.479315Z", "iopub.status.idle": "2025-03-25T06:34:04.648052Z", "shell.execute_reply": "2025-03-25T06:34:04.647686Z" } }, "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 = \"GSE235307\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Arrhythmia\"\n", "in_cohort_dir = \"../../input/GEO/Arrhythmia/GSE235307\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Arrhythmia/GSE235307.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Arrhythmia/gene_data/GSE235307.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Arrhythmia/clinical_data/GSE235307.csv\"\n", "json_path = \"../../output/preprocess/Arrhythmia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d30bfd9d", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "cdeee471", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:34:04.649489Z", "iopub.status.busy": "2025-03-25T06:34:04.649346Z", "iopub.status.idle": "2025-03-25T06:34:05.074753Z", "shell.execute_reply": "2025-03-25T06:34:05.074392Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression and atrial fibrillation prediction\"\n", "!Series_summary\t\"The aim of this study was to identify a blood gene expression profile that predicts atrial fibrillation in heart failure patients\"\n", "!Series_overall_design\t\"Cardiac blood samples were obtained from the coronary sinus during CRT-D (Cardiac Resynchronization Therapy - Defibrillator) placement in heart failure patients. Patients were followed during 1 year.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Whole blood'], 1: ['gender: Male', 'gender: Female'], 2: ['age: 63', 'age: 60', 'age: 72', 'age: 66', 'age: 70', 'age: 64', 'age: 61', 'age: 44', 'age: 54', 'age: 50', 'age: 79', 'age: 51', 'age: 55', 'age: 67', 'age: 52', 'age: 73', 'age: 76', 'age: 43', 'age: 68', 'age: 78', 'age: 69', 'age: 57', 'age: 59', 'age: 53', 'age: 65', 'age: 56', 'age: 74', 'age: 38', 'age: 71', 'age: 37'], 3: ['cardiopathy: ischemic', 'cardiopathy: non ischemic', 'cardiopathy: mixed'], 4: ['cardiac rhythm at start of the study: Sinus rhythm'], 5: ['cardiac rhythm after 1 year follow-up: Sinus rhythm', 'cardiac rhythm after 1 year follow-up: Atrial fibrillation']}\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": "926c72bd", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b925bfe5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:34:05.076575Z", "iopub.status.busy": "2025-03-25T06:34:05.076427Z", "iopub.status.idle": "2025-03-25T06:34:05.093802Z", "shell.execute_reply": "2025-03-25T06:34:05.093492Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview: {'GSM7498589': [0.0, 63.0, 1.0], 'GSM7498590': [0.0, 60.0, 1.0], 'GSM7498591': [0.0, 60.0, 1.0], 'GSM7498592': [0.0, 72.0, 1.0], 'GSM7498593': [0.0, 63.0, 1.0], 'GSM7498594': [0.0, 66.0, 1.0], 'GSM7498595': [0.0, 70.0, 1.0], 'GSM7498596': [0.0, 64.0, 1.0], 'GSM7498597': [0.0, 63.0, 1.0], 'GSM7498598': [0.0, 61.0, 1.0], 'GSM7498599': [0.0, 70.0, 1.0], 'GSM7498600': [0.0, 64.0, 1.0], 'GSM7498601': [0.0, 63.0, 1.0], 'GSM7498602': [0.0, 44.0, 1.0], 'GSM7498603': [0.0, 54.0, 1.0], 'GSM7498604': [0.0, 44.0, 1.0], 'GSM7498605': [0.0, 50.0, 1.0], 'GSM7498606': [1.0, 79.0, 1.0], 'GSM7498607': [0.0, 63.0, 1.0], 'GSM7498608': [0.0, 63.0, 1.0], 'GSM7498609': [1.0, 64.0, 1.0], 'GSM7498610': [0.0, 60.0, 1.0], 'GSM7498611': [0.0, 51.0, 1.0], 'GSM7498612': [0.0, 55.0, 1.0], 'GSM7498613': [0.0, 55.0, 1.0], 'GSM7498614': [1.0, 67.0, 1.0], 'GSM7498615': [0.0, 52.0, 1.0], 'GSM7498616': [0.0, 70.0, 1.0], 'GSM7498617': [0.0, 54.0, 1.0], 'GSM7498618': [0.0, 54.0, 1.0], 'GSM7498619': [0.0, 73.0, 1.0], 'GSM7498620': [0.0, 54.0, 1.0], 'GSM7498621': [0.0, 76.0, 1.0], 'GSM7498622': [0.0, 76.0, 1.0], 'GSM7498623': [0.0, 43.0, 1.0], 'GSM7498624': [0.0, 64.0, 1.0], 'GSM7498625': [0.0, 64.0, 1.0], 'GSM7498626': [0.0, 68.0, 1.0], 'GSM7498627': [0.0, 43.0, 1.0], 'GSM7498628': [1.0, 54.0, 1.0], 'GSM7498629': [0.0, 72.0, 1.0], 'GSM7498630': [0.0, 51.0, 1.0], 'GSM7498631': [0.0, 68.0, 1.0], 'GSM7498632': [0.0, 50.0, 1.0], 'GSM7498633': [0.0, 78.0, 1.0], 'GSM7498634': [1.0, 69.0, 1.0], 'GSM7498635': [0.0, 64.0, 1.0], 'GSM7498636': [0.0, 54.0, 1.0], 'GSM7498637': [0.0, 54.0, 1.0], 'GSM7498638': [0.0, 57.0, 1.0], 'GSM7498639': [0.0, 55.0, 1.0], 'GSM7498640': [0.0, 60.0, 1.0], 'GSM7498641': [0.0, 59.0, 1.0], 'GSM7498642': [0.0, 54.0, 1.0], 'GSM7498643': [0.0, 54.0, 1.0], 'GSM7498644': [0.0, 54.0, 1.0], 'GSM7498645': [0.0, 54.0, 1.0], 'GSM7498646': [0.0, 53.0, 1.0], 'GSM7498647': [0.0, 52.0, 1.0], 'GSM7498648': [0.0, 68.0, 1.0], 'GSM7498649': [0.0, 72.0, 1.0], 'GSM7498650': [0.0, 70.0, 1.0], 'GSM7498651': [0.0, 65.0, 1.0], 'GSM7498652': [0.0, 64.0, 1.0], 'GSM7498653': [0.0, 56.0, 1.0], 'GSM7498654': [0.0, 56.0, 1.0], 'GSM7498655': [0.0, 63.0, 1.0], 'GSM7498656': [0.0, 57.0, 1.0], 'GSM7498657': [0.0, 63.0, 1.0], 'GSM7498658': [0.0, 68.0, 1.0], 'GSM7498659': [0.0, 66.0, 1.0], 'GSM7498660': [0.0, 74.0, 1.0], 'GSM7498661': [0.0, 38.0, 1.0], 'GSM7498662': [0.0, 56.0, 1.0], 'GSM7498663': [0.0, 57.0, 1.0], 'GSM7498664': [0.0, 71.0, 1.0], 'GSM7498665': [1.0, 78.0, 1.0], 'GSM7498666': [0.0, 51.0, 1.0], 'GSM7498667': [0.0, 50.0, 1.0], 'GSM7498668': [0.0, 37.0, 1.0], 'GSM7498669': [0.0, 37.0, 1.0], 'GSM7498670': [0.0, 70.0, 1.0], 'GSM7498671': [0.0, 72.0, 1.0], 'GSM7498672': [0.0, 73.0, 1.0], 'GSM7498673': [0.0, 69.0, 1.0], 'GSM7498674': [0.0, 69.0, 1.0], 'GSM7498675': [1.0, 63.0, 1.0], 'GSM7498676': [0.0, 62.0, 1.0], 'GSM7498677': [0.0, 59.0, 1.0], 'GSM7498678': [0.0, 67.0, 1.0], 'GSM7498679': [0.0, 76.0, 1.0], 'GSM7498680': [0.0, 63.0, 1.0], 'GSM7498681': [0.0, 55.0, 1.0], 'GSM7498682': [0.0, 57.0, 1.0], 'GSM7498683': [0.0, 53.0, 1.0], 'GSM7498684': [0.0, 59.0, 1.0], 'GSM7498685': [1.0, 77.0, 1.0], 'GSM7498686': [0.0, 54.0, 1.0], 'GSM7498687': [1.0, 64.0, 1.0], 'GSM7498688': [0.0, 75.0, 1.0], 'GSM7498689': [0.0, 75.0, 1.0], 'GSM7498690': [0.0, 72.0, 1.0], 'GSM7498691': [0.0, 58.0, 1.0], 'GSM7498692': [0.0, 75.0, 1.0], 'GSM7498693': [0.0, 78.0, 1.0], 'GSM7498694': [0.0, 58.0, 1.0], 'GSM7498695': [0.0, 64.0, 1.0], 'GSM7498696': [0.0, 63.0, 1.0], 'GSM7498697': [0.0, 61.0, 1.0], 'GSM7498698': [0.0, 60.0, 1.0], 'GSM7498699': [0.0, 59.0, 1.0], 'GSM7498700': [0.0, 68.0, 1.0], 'GSM7498701': [0.0, 77.0, 1.0], 'GSM7498702': [1.0, 57.0, 1.0], 'GSM7498703': [0.0, 62.0, 1.0], 'GSM7498704': [1.0, 66.0, 1.0], 'GSM7498705': [1.0, 57.0, 1.0], 'GSM7498706': [1.0, 65.0, 1.0], 'GSM7498707': [0.0, 59.0, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Arrhythmia/clinical_data/GSE235307.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "\n", "# 1. Gene Expression Data Availability\n", "is_gene_available = True # Based on Series info, this seems to be a gene expression dataset\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "trait_row = 5 # \"cardiac rhythm after 1 year follow-up\" indicates Atrial fibrillation presence\n", "age_row = 2 # Age information is available in row 2\n", "gender_row = 1 # Gender information is available in row 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary: 1 for atrial fibrillation, 0 for sinus rhythm.\"\"\"\n", " if value is None or not isinstance(value, str):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if 'atrial fibrillation' in value:\n", " return 1\n", " elif 'sinus rhythm' in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to a continuous numeric value.\"\"\"\n", " if value is None or not isinstance(value, str):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " else:\n", " value = value.strip()\n", " \n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary: 1 for male, 0 for female.\"\"\"\n", " if value is None or not isinstance(value, str):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if 'male' in value:\n", " return 1\n", " elif 'female' in value:\n", " return 0\n", " return None\n", "\n", "# 3. Save Metadata - Initial filtering\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Ensure the directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Assuming clinical_df is available from a previous step\n", " # If not available, we would need to load it first\n", " try:\n", " # Extract clinical features using the correct parameter name\n", " clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data, # Use the existing clinical_data variable\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the data\n", " preview = preview_df(clinical_df)\n", " print(\"Clinical Data Preview:\", preview)\n", " \n", " # Save to CSV\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except NameError:\n", " print(\"Error: clinical_data is not defined. Make sure to load the clinical data first.\")\n" ] }, { "cell_type": "markdown", "id": "c95f1342", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "be99b4d5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:34:05.095372Z", "iopub.status.busy": "2025-03-25T06:34:05.095233Z", "iopub.status.idle": "2025-03-25T06:34:05.882123Z", "shell.execute_reply": "2025-03-25T06:34:05.881723Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Arrhythmia/GSE235307/GSE235307_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (58717, 119)\n", "First 20 gene/probe identifiers:\n", "Index(['4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16',\n", " '17', '18', '19', '20', '21', '22', '23'],\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": "b4ea7e43", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d352d7e5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:34:05.883876Z", "iopub.status.busy": "2025-03-25T06:34:05.883722Z", "iopub.status.idle": "2025-03-25T06:34:05.885896Z", "shell.execute_reply": "2025-03-25T06:34:05.885610Z" } }, "outputs": [], "source": [ "# Reviewing the gene identifiers presented in the previous step\n", "# The identifiers appear to be numeric values (4, 5, 6, etc.) rather than standard gene symbols\n", "# Human gene symbols would typically be alphanumeric (like BRCA1, TP53, etc.)\n", "# These numeric identifiers need to be mapped to standard gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "e3416c19", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "9666b275", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:34:05.887477Z", "iopub.status.busy": "2025-03-25T06:34:05.887370Z", "iopub.status.idle": "2025-03-25T06:34:48.462231Z", "shell.execute_reply": "2025-03-25T06:34:48.461818Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'COL', 'ROW', 'NAME', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'LOCUSLINK_ID', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n", "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['192', '192', '192', '192', '192'], 'ROW': [328.0, 326.0, 324.0, 322.0, 320.0], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_015987', 'NM_080671'], 'GB_ACC': [nan, nan, nan, 'NM_015987', 'NM_080671'], 'LOCUSLINK_ID': [nan, nan, nan, 50865.0, 23704.0], 'GENE_SYMBOL': [nan, nan, nan, 'HEBP1', 'KCNE4'], 'GENE_NAME': [nan, nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.642618', 'Hs.348522'], 'ENSEMBL_ID': [nan, nan, nan, 'ENST00000014930', 'ENST00000281830'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788'], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256'], 'CYTOBAND': [nan, nan, nan, 'hs|12p13.1', 'hs|2q36.1'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens heme binding protein 1 (HEBP1), mRNA [NM_015987]', 'Homo sapiens potassium voltage-gated channel, Isk-related family, member 4 (KCNE4), mRNA [NM_080671]'], 'GO_ID': [nan, nan, nan, 'GO:0005488(binding)|GO:0005576(extracellular region)|GO:0005737(cytoplasm)|GO:0005739(mitochondrion)|GO:0005829(cytosol)|GO:0007623(circadian rhythm)|GO:0020037(heme binding)', 'GO:0005244(voltage-gated ion channel activity)|GO:0005249(voltage-gated potassium channel activity)|GO:0006811(ion transport)|GO:0006813(potassium ion transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0016324(apical plasma membrane)'], 'SEQUENCE': [nan, nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT']}\n", "\n", "Analyzing SPOT_ID.1 column for gene symbols:\n", "\n", "Gene data ID prefix: 4\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'ID' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'COL' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'ROW' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'NAME' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'SPOT_ID' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'REFSEQ' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'GB_ACC' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'LOCUSLINK_ID' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'GENE_SYMBOL' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'GENE_NAME' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'UNIGENE_ID' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'ENSEMBL_ID' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'ACCESSION_STRING' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'CHROMOSOMAL_LOCATION' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'CYTOBAND' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'DESCRIPTION' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'GO_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 'NAME' may contain gene-related information\n", "Sample values: ['GE_BrightCorner', 'DarkCorner', 'DarkCorner']\n", "Column 'GENE_SYMBOL' may contain gene-related information\n", "Sample values: [nan, nan, nan]\n", "Column 'GENE_NAME' 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 'DESCRIPTION' may contain gene-related information\n", "Sample values: [nan, nan, nan]\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": "dce7a22e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "6ea8bf5d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:34:48.464063Z", "iopub.status.busy": "2025-03-25T06:34:48.463929Z", "iopub.status.idle": "2025-03-25T06:34:51.867601Z", "shell.execute_reply": "2025-03-25T06:34:51.867205Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (54295, 2)\n", "Gene mapping preview:\n", " ID Gene\n", "3 4 HEBP1\n", "4 5 KCNE4\n", "5 6 BPIFA3\n", "6 7 LOC100129869\n", "7 8 IRG1\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data after mapping: (20353, 119)\n", "First few genes and samples:\n", " GSM7498589 GSM7498590 GSM7498591\n", "Gene \n", "A1BG 1215.921532 1042.240181 860.505266\n", "A1BG-AS1 167.933502 156.514231 153.778492\n", "A1CF 590.313903 592.863373 596.313839\n", "A2LD1 270.359499 377.943542 351.312844\n", "A2M 555.994327 688.515352 651.543646\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Arrhythmia/gene_data/GSE235307.csv\n" ] } ], "source": [ "# 1. Determine which columns contain the probe IDs and gene symbols\n", "# Based on the previous outputs:\n", "# - 'ID' column in gene_annotation contains numeric identifiers that match gene_data indices\n", "# - 'GENE_SYMBOL' column contains the gene symbols we need to map to\n", "\n", "# 2. Get gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"Gene mapping preview:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# This uses the provided function that handles many-to-many mappings\n", "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)\n", "print(f\"Gene expression data after mapping: {gene_data.shape}\")\n", "print(\"First few genes and samples:\")\n", "print(gene_data.iloc[:5, :3])\n", "\n", "# 4. Save the gene data to a 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 expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "e5c2f35b", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "4377b4d1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:34:51.869432Z", "iopub.status.busy": "2025-03-25T06:34:51.869308Z", "iopub.status.idle": "2025-03-25T06:35:08.229858Z", "shell.execute_reply": "2025-03-25T06:35:08.229441Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (20353, 119)\n", "Gene data shape after normalization: (19847, 119)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Arrhythmia/gene_data/GSE235307.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original clinical data preview:\n", " !Sample_geo_accession \\\n", "0 !Sample_characteristics_ch1 \n", "1 !Sample_characteristics_ch1 \n", "2 !Sample_characteristics_ch1 \n", "3 !Sample_characteristics_ch1 \n", "4 !Sample_characteristics_ch1 \n", "\n", " GSM7498589 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 63 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498590 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 60 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498591 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 60 \n", "3 cardiopathy: non ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498592 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 72 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498593 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 63 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498594 \\\n", "0 tissue: Whole blood \n", "1 gender: Female \n", "2 age: 66 \n", "3 cardiopathy: non ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498595 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 70 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498596 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 64 \n", "3 cardiopathy: non ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498597 ... \\\n", "0 tissue: Whole blood ... \n", "1 gender: Male ... \n", "2 age: 63 ... \n", "3 cardiopathy: ischemic ... \n", "4 cardiac rhythm at start of the study: Sinus rh... ... \n", "\n", " GSM7498698 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 60 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498699 \\\n", "0 tissue: Whole blood \n", "1 gender: Female \n", "2 age: 59 \n", "3 cardiopathy: non ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498700 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 68 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498701 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 77 \n", "3 cardiopathy: non ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498702 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 57 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498703 \\\n", "0 tissue: Whole blood \n", "1 gender: Female \n", "2 age: 62 \n", "3 cardiopathy: non ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498704 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 66 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498705 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 57 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498706 \\\n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 65 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", " GSM7498707 \n", "0 tissue: Whole blood \n", "1 gender: Male \n", "2 age: 59 \n", "3 cardiopathy: ischemic \n", "4 cardiac rhythm at start of the study: Sinus rh... \n", "\n", "[5 rows x 120 columns]\n", "Selected clinical data shape: (3, 119)\n", "Clinical data preview:\n", " GSM7498589 GSM7498590 GSM7498591 GSM7498592 GSM7498593 \\\n", "Arrhythmia 0.0 0.0 0.0 0.0 0.0 \n", "Age 63.0 60.0 60.0 72.0 63.0 \n", "Gender 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM7498594 GSM7498595 GSM7498596 GSM7498597 GSM7498598 ... \\\n", "Arrhythmia 0.0 0.0 0.0 0.0 0.0 ... \n", "Age 66.0 70.0 64.0 63.0 61.0 ... \n", "Gender 1.0 1.0 1.0 1.0 1.0 ... \n", "\n", " GSM7498698 GSM7498699 GSM7498700 GSM7498701 GSM7498702 \\\n", "Arrhythmia 0.0 0.0 0.0 0.0 1.0 \n", "Age 60.0 59.0 68.0 77.0 57.0 \n", "Gender 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM7498703 GSM7498704 GSM7498705 GSM7498706 GSM7498707 \n", "Arrhythmia 0.0 1.0 1.0 1.0 0.0 \n", "Age 62.0 66.0 57.0 65.0 59.0 \n", "Gender 1.0 1.0 1.0 1.0 1.0 \n", "\n", "[3 rows x 119 columns]\n", "Linked data shape before processing: (119, 19850)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Arrhythmia Age Gender A1BG A1BG-AS1\n", "GSM7498589 0.0 63.0 1.0 1215.921532 167.933502\n", "GSM7498590 0.0 60.0 1.0 1042.240181 156.514231\n", "GSM7498591 0.0 60.0 1.0 860.505266 153.778492\n", "GSM7498592 0.0 72.0 1.0 1016.786080 164.688762\n", "GSM7498593 0.0 63.0 1.0 930.371907 153.624856\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (119, 19850)\n", "For the feature 'Arrhythmia', the least common label is '1.0' with 13 occurrences. This represents 10.92% of the dataset.\n", "The distribution of the feature 'Arrhythmia' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 55.0\n", " 50% (Median): 63.0\n", " 75%: 68.0\n", "Min: 37.0\n", "Max: 79.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 119 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after removing biased features: (119, 19849)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Arrhythmia/GSE235307.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 }