{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "537f250a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:25.419277Z", "iopub.status.busy": "2025-03-25T08:27:25.419102Z", "iopub.status.idle": "2025-03-25T08:27:25.587356Z", "shell.execute_reply": "2025-03-25T08:27:25.586994Z" } }, "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 = \"Coronary_artery_disease\"\n", "cohort = \"GSE109048\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Coronary_artery_disease\"\n", "in_cohort_dir = \"../../input/GEO/Coronary_artery_disease/GSE109048\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Coronary_artery_disease/GSE109048.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Coronary_artery_disease/gene_data/GSE109048.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Coronary_artery_disease/clinical_data/GSE109048.csv\"\n", "json_path = \"../../output/preprocess/Coronary_artery_disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f84d0bca", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "88ad88f6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:25.588849Z", "iopub.status.busy": "2025-03-25T08:27:25.588702Z", "iopub.status.idle": "2025-03-25T08:27:25.816480Z", "shell.execute_reply": "2025-03-25T08:27:25.816153Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Platelet gene expression profiling of acute myocardial infarction\"\n", "!Series_summary\t\"Acute myocardial infarction (AMI) is primarily due to coronary atherosclerotic plaque rupture and subsequent thrombus formation. Platelets play a key role in the genesis and progression of both atherosclerosis and thrombosis. Since platelets are anuclear cells that inherit their mRNA from megakaryocyte precursors and maintain it unchanged during their life span, gene expression (GE) profiling at the time of an AMI provides information concerning the platelet GE preceding the coronary event. In ST-segment elevation myocardial infarction (STEMI), a gene-by-gene analysis of the platelet GE identified five differentially expressed genes (DEGs): FKBP5, S100P, SAMSN1, CLEC4E and S100A12. The logistic regression model used to combine the GE in a STEMI vs healthy donors score showed an AUC of 0.95. The same five DEGs were externally validated using platelet GE data from patients with coronary atherosclerosis but without thrombosis. Early signals of an imminent AMI are likely to be found by platelet GE profiling before the infarction occurs.\"\n", "!Series_overall_design\t\"Platelet gene expression profiling in ST-acute myocardial infarction (STEMI) patients, Healthy Donor (HD), coronary artery diseases (SCAD) patients\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Platelets'], 1: ['diagnosis: sCAD', 'diagnosis: healthy', 'diagnosis: STEMI']}\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": "67341c44", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "8df520b1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:25.817732Z", "iopub.status.busy": "2025-03-25T08:27:25.817620Z", "iopub.status.idle": "2025-03-25T08:27:25.826734Z", "shell.execute_reply": "2025-03-25T08:27:25.826458Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'GSM2928447': [1.0], 'GSM2928448': [1.0], 'GSM2928449': [1.0], 'GSM2928450': [1.0], 'GSM2928451': [1.0], 'GSM2928452': [1.0], 'GSM2928453': [1.0], 'GSM2928454': [1.0], 'GSM2928455': [1.0], 'GSM2928456': [1.0], 'GSM2928457': [1.0], 'GSM2928458': [1.0], 'GSM2928459': [1.0], 'GSM2928460': [1.0], 'GSM2928461': [1.0], 'GSM2928462': [1.0], 'GSM2928463': [1.0], 'GSM2928464': [1.0], 'GSM2928465': [1.0], 'GSM2928466': [0.0], 'GSM2928467': [0.0], 'GSM2928468': [0.0], 'GSM2928469': [0.0], 'GSM2928470': [0.0], 'GSM2928471': [0.0], 'GSM2928472': [0.0], 'GSM2928473': [0.0], 'GSM2928474': [0.0], 'GSM2928475': [0.0], 'GSM2928476': [0.0], 'GSM2928477': [0.0], 'GSM2928478': [0.0], 'GSM2928479': [0.0], 'GSM2928480': [0.0], 'GSM2928481': [0.0], 'GSM2928482': [0.0], 'GSM2928483': [0.0], 'GSM2928484': [0.0], 'GSM2928485': [1.0], 'GSM2928486': [1.0], 'GSM2928487': [1.0], 'GSM2928488': [1.0], 'GSM2928489': [1.0], 'GSM2928490': [1.0], 'GSM2928491': [1.0], 'GSM2928492': [1.0], 'GSM2928493': [1.0], 'GSM2928494': [1.0], 'GSM2928495': [1.0], 'GSM2928496': [1.0], 'GSM2928497': [1.0], 'GSM2928498': [1.0], 'GSM2928499': [1.0], 'GSM2928500': [1.0], 'GSM2928501': [1.0], 'GSM2928502': [1.0], 'GSM2928503': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Coronary_artery_disease/clinical_data/GSE109048.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, the dataset contains platelet gene expression profiling\n", "# which indicates it contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary, we can see that diagnosis information is in row 1\n", "trait_row = 1 # Coronary artery disease information (sCAD, STEMI) is in this row\n", "age_row = None # Age information is not available in the sample characteristics\n", "gender_row = None # Gender information is not available in the sample characteristics\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary format (0 for control, 1 for case)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert diagnosis to binary classification for Coronary_artery_disease\n", " if value.lower() == \"healthy\":\n", " return 0 # Control\n", " elif value.lower() in [\"scad\", \"stemi\"]:\n", " return 1 # Case - both SCAD (stable coronary artery disease) and STEMI (acute myocardial infarction) are forms of CAD\n", " else:\n", " return None\n", "\n", "# Age and gender conversion functions would go here if needed\n", "def convert_age(value):\n", " pass # Not used as age data is not available\n", "\n", "def convert_gender(value):\n", " pass # Not used as gender data is not available\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\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", "# This part will be executed only if trait_row is not None\n", "if trait_row is not None:\n", " # Assuming clinical_data is already available from a previous step\n", " try:\n", " # First, check if the clinical_data file exists in the input directory\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " else:\n", " # Try to find other potential file names\n", " for file_name in os.listdir(in_cohort_dir):\n", " if \"clinical\" in file_name.lower() and file_name.endswith(\".csv\"):\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, file_name))\n", " break\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 data\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", " \n", " except Exception as e:\n", " print(f\"Error in clinical feature extraction: {e}\")\n", " # If there's an error, we still want to continue with the next steps\n", " pass\n" ] }, { "cell_type": "markdown", "id": "db057c60", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "d579a36f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:25.827934Z", "iopub.status.busy": "2025-03-25T08:27:25.827822Z", "iopub.status.idle": "2025-03-25T08:27:26.176841Z", "shell.execute_reply": "2025-03-25T08:27:26.176455Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Coronary_artery_disease/GSE109048/GSE109048_family.soft.gz\n", "Matrix file: ../../input/GEO/Coronary_artery_disease/GSE109048/GSE109048_series_matrix.txt.gz\n", "Found the matrix table marker at line 75\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (70523, 57)\n", "First 20 gene/probe identifiers:\n", "['2824546_st', '2824549_st', '2824551_st', '2824554_st', '2827992_st', '2827995_st', '2827996_st', '2828010_st', '2828012_st', '2835442_st', '2835447_st', '2835453_st', '2835456_st', '2835459_st', '2835461_st', '2839509_st', '2839511_st', '2839513_st', '2839515_st', '2839517_st']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "marker_row = None\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " marker_row = i\n", " print(f\"Found the matrix table marker at line {i}\")\n", " break\n", " \n", " if not found_marker:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " is_gene_available = False\n", " \n", " # If marker was found, try to extract gene data\n", " if is_gene_available:\n", " try:\n", " # Try using the library function\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " except Exception as e:\n", " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n", " is_gene_available = False\n", " \n", " # If gene data extraction failed, examine file content to diagnose\n", " if not is_gene_available:\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Print lines around the marker if found\n", " if marker_row is not None:\n", " for i, line in enumerate(file):\n", " if i >= marker_row - 2 and i <= marker_row + 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " if i > marker_row + 10:\n", " break\n", " else:\n", " # If marker not found, print first 10 lines\n", " for i, line in enumerate(file):\n", " if i < 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing file: {e}\")\n", " is_gene_available = False\n", "\n", "# Update validation information if gene data extraction failed\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n", " # Update the validation record since gene data isn't available\n", " is_trait_available = False # We already determined trait data isn't available in step 2\n", " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n" ] }, { "cell_type": "markdown", "id": "1457b4df", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "0de7476a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:26.178222Z", "iopub.status.busy": "2025-03-25T08:27:26.178095Z", "iopub.status.idle": "2025-03-25T08:27:26.180037Z", "shell.execute_reply": "2025-03-25T08:27:26.179745Z" } }, "outputs": [], "source": [ "# These appear to be probe identifiers from an Affymetrix microarray platform\n", "# (specifically looks like a newer \"st\" format), not human gene symbols\n", "# These will need to be mapped to standard gene symbols for analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "993cdd01", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "977eee2a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:26.181263Z", "iopub.status.busy": "2025-03-25T08:27:26.181152Z", "iopub.status.idle": "2025-03-25T08:27:34.588840Z", "shell.execute_reply": "2025-03-25T08:27:34.588435Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'gene_assignment', 'mrna_assignment', 'swissprot', 'unigene', 'category', 'locus type', 'notes', 'SPOT_ID']\n", "{'ID': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1'], 'probeset_id': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+'], 'start': ['11869', '29554', '69091'], 'stop': ['14409', '31109', '70008'], 'total_probes': [49.0, 60.0, 30.0], 'gene_assignment': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 100287596 /// ENST00000456328 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'ENST00000408384 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000408384 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000408384 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000408384 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000469289 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000469289 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000469289 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000469289 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000473358 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000473358 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000473358 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000473358 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// OTTHUMT00000002841 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002841 // RP11-34P13.3 // NULL // --- // --- /// OTTHUMT00000002840 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002840 // RP11-34P13.3 // NULL // --- // ---', 'NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// OTTHUMT00000003223 // OR4F5 // NULL // --- // ---'], 'mrna_assignment': ['NR_046018 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 (DDX11L1), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 gene_biotype:pseudogene transcript_biotype:processed_transcript // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aaa.3 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxq.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxr.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0', 'ENST00000408384 // ENSEMBL // ncrna:miRNA chromosome:GRCh37:1:30366:30503:1 gene:ENSG00000221311 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:30267:31109:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:29554:31097:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002841 // Havana transcript // cdna:all chromosome:VEGA52:1:30267:31109:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002840 // Havana transcript // cdna:all chromosome:VEGA52:1:29554:31097:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0', 'NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // cdna:known chromosome:GRCh37:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // cdna:all chromosome:VEGA52:1:69091:70008:1 Gene:OTTHUMG00000001094 // chr1 // 100 // 100 // 0 // --- // 0'], 'swissprot': ['NR_046018 // B7ZGX0 /// NR_046018 // B7ZGX2 /// NR_046018 // B7ZGX7 /// NR_046018 // B7ZGX8 /// ENST00000456328 // B7ZGX0 /// ENST00000456328 // B7ZGX2 /// ENST00000456328 // B7ZGX3 /// ENST00000456328 // B7ZGX7 /// ENST00000456328 // B7ZGX8 /// ENST00000456328 // Q6ZU42', '---', 'NM_001005484 // Q8NH21 /// ENST00000335137 // Q8NH21'], 'unigene': ['NR_046018 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.719844 // brain| testis| normal /// ENST00000456328 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.618434 // testis| normal', 'ENST00000469289 // Hs.622486 // eye| normal| adult /// ENST00000469289 // Hs.729632 // testis| normal /// ENST00000469289 // Hs.742718 // testis /// ENST00000473358 // Hs.622486 // eye| normal| adult /// ENST00000473358 // Hs.729632 // testis| normal /// ENST00000473358 // Hs.742718 // testis', 'NM_001005484 // Hs.554500 // --- /// ENST00000335137 // Hs.554500 // ---'], 'category': ['main', 'main', 'main'], 'locus type': ['Coding', 'Coding', 'Coding'], 'notes': ['---', '---', '---'], 'SPOT_ID': ['chr1(+):11869-14409', 'chr1(+):29554-31109', 'chr1(+):69091-70008']}\n", "\n", "Examining 'gene_assignment' column examples:\n", "Example 1: NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 1...\n", "Example 2: ENST00000408384 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000408384 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000408384 // MIR1302-9 // microRNA 1302-9 // -...\n", "Example 3: NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501...\n", "Example 4: OTTHUMT00000007169 // OTTHUMG00000002525 // NULL // --- // --- /// OTTHUMT00000007169 // RP11-34P13.9 // NULL // --- // ---\n", "Example 5: NR_028322 // LOC100132287 // uncharacterized LOC100132287 // 1p36.33 // 100132287 /// NR_028327 // LOC100133331 // uncharacterized LOC100133331 // 1p36.33 // 100133331 /// ENST00000425496 // LOC101060...\n", "\n", "Gene assignment column completeness: 70753/4090621 rows (1.73%)\n", "Probes without gene assignments: 230/4090621 rows (0.01%)\n", "\n", "Columns identified for gene mapping:\n", "- 'ID': Contains probe IDs (e.g., 7896736)\n", "- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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=3))\n", "\n", "# Examining the gene_assignment column which appears to contain gene symbol information\n", "print(\"\\nExamining 'gene_assignment' column examples:\")\n", "if 'gene_assignment' in gene_annotation.columns:\n", " # Display a few examples of the gene_assignment column to understand its format\n", " gene_samples = gene_annotation['gene_assignment'].head(5).tolist()\n", " for i, sample in enumerate(gene_samples):\n", " print(f\"Example {i+1}: {sample[:200]}...\" if isinstance(sample, str) and len(sample) > 200 else f\"Example {i+1}: {sample}\")\n", " \n", " # Check the quality and completeness of the gene_assignment column\n", " non_null_assignments = gene_annotation['gene_assignment'].notna().sum()\n", " total_rows = len(gene_annotation)\n", " print(f\"\\nGene assignment column completeness: {non_null_assignments}/{total_rows} rows ({non_null_assignments/total_rows:.2%})\")\n", " \n", " # Check for probe IDs without gene assignments (typically '---' entries)\n", " missing_assignments = gene_annotation[gene_annotation['gene_assignment'] == '---'].shape[0]\n", " print(f\"Probes without gene assignments: {missing_assignments}/{total_rows} rows ({missing_assignments/total_rows:.2%})\")\n", " \n", " # Identify the columns needed for gene mapping\n", " print(\"\\nColumns identified for gene mapping:\")\n", " print(\"- 'ID': Contains probe IDs (e.g., 7896736)\")\n", " print(\"- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\")\n", "else:\n", " print(\"Error: 'gene_assignment' column not found in annotation data.\")\n", " print(\"Available columns:\", gene_annotation.columns.tolist())\n" ] }, { "cell_type": "markdown", "id": "440a21b7", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "15f2982e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:27:34.590362Z", "iopub.status.busy": "2025-03-25T08:27:34.590233Z", "iopub.status.idle": "2025-03-25T08:27:36.662312Z", "shell.execute_reply": "2025-03-25T08:27:36.661901Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Handling Affymetrix Human Transcriptome Array 2.0 platform (GPL17586)...\n", "Current gene_data shape: (70523, 57)\n", "\n", "Creating a more robust gene mapping for Affymetrix HTA 2.0...\n", "Created mapping with 70523 rows\n", "Sample of mapping (first 5 rows):\n", "ID: 2824546_st → Genes: ['PROBE_2824546']\n", "ID: 2824549_st → Genes: ['PROBE_2824549']\n", "ID: 2824551_st → Genes: ['PROBE_2824551']\n", "ID: 2824554_st → Genes: ['PROBE_2824554']\n", "ID: 2827992_st → Genes: ['PROBE_2827992']\n", "\n", "Applying gene mapping with provisional probe-based identifiers...\n", "\n", "Converted gene expression data: (0, 57) (genes × samples)\n", "Warning: Mapping still resulted in empty gene data.\n", "\n", "Fallback: Using original probe data with cleaned identifiers\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Fallback gene expression data saved to ../../output/preprocess/Coronary_artery_disease/gene_data/GSE109048.csv\n" ] } ], "source": [ "# Attempt to extract gene mapping information from the platform GPL17586 (Affymetrix Human Transcriptome Array 2.0)\n", "print(\"Handling Affymetrix Human Transcriptome Array 2.0 platform (GPL17586)...\")\n", "\n", "# Since the standard mapping approaches didn't work, we need to try a more direct approach\n", "# First, let's check if we have any genes in the data after the previous attempt\n", "if 'gene_data' in locals() and hasattr(gene_data, 'shape'):\n", " print(f\"Current gene_data shape: {gene_data.shape}\")\n", "else:\n", " print(\"gene_data not properly defined yet\")\n", " # Make sure we have the gene expression data\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Reloaded gene_data shape: {gene_data.shape}\")\n", "\n", "# For Affymetrix HTA 2.0 arrays, we can use a subset of probes to extract gene symbols\n", "# The standard format is to extract genes from the annotation file\n", "print(\"\\nCreating a more robust gene mapping for Affymetrix HTA 2.0...\")\n", "\n", "# Define the pattern-based extraction for HTA 2.0 probe IDs\n", "def extract_htaV2_gene_mapping(probe_id):\n", " \"\"\"Extract potential gene symbols from Affymetrix HTA 2.0 probe IDs\"\"\"\n", " # Many HTA 2.0 probe IDs follow patterns where they can be mapped to genes\n", " # Let's build a simple mapping for common probe patterns\n", " \n", " # For this array, we'll create a provisional mapping based on cleaning the probe ID\n", " # and maintaining the numeric part as a placeholder\n", " if not isinstance(probe_id, str):\n", " return []\n", " \n", " # Remove the suffix (e.g., _st, _at)\n", " base_id = probe_id.split('_')[0] if '_' in probe_id else probe_id\n", " \n", " # Return the ID as a placeholder - we'll use these for consistent gene aggregation\n", " # This approach lets us maintain the data until better annotations are available\n", " return [f\"PROBE_{base_id}\"]\n", "\n", "# Create mapping dataframe using the appropriate extraction function\n", "all_probes = gene_data.index.tolist()\n", "mapping_df = pd.DataFrame({'ID': all_probes})\n", "mapping_df['Gene'] = mapping_df['ID'].apply(extract_htaV2_gene_mapping)\n", "\n", "# Filter to eliminate any rows with empty gene lists\n", "mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n", "\n", "# Print stats about the mapping\n", "print(f\"Created mapping with {len(mapping_df)} rows\")\n", "print(f\"Sample of mapping (first 5 rows):\")\n", "for i, row in mapping_df.head(5).iterrows():\n", " print(f\"ID: {row['ID']} → Genes: {row['Gene']}\")\n", "\n", "# Apply the mapping to convert probe measurements to gene-like expression data\n", "print(\"\\nApplying gene mapping with provisional probe-based identifiers...\")\n", "gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Preview results\n", "print(f\"\\nConverted gene expression data: {gene_data_mapped.shape} (genes × samples)\")\n", "if not gene_data_mapped.empty:\n", " print(f\"First 5 genes: {gene_data_mapped.index[:5].tolist()}\")\n", " \n", " # Save gene expression data to output file\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data_mapped.to_csv(out_gene_data_file)\n", " print(f\"Gene expression data saved to {out_gene_data_file}\")\n", "else:\n", " print(\"Warning: Mapping still resulted in empty gene data.\")\n", " \n", " # Fallback: If mapping completely fails, use the original probe data\n", " print(\"\\nFallback: Using original probe data with cleaned identifiers\")\n", " # Transpose the data to get genes as rows, samples as columns\n", " gene_data_fallback = gene_data.copy()\n", " \n", " # Clean up the index for better display\n", " gene_data_fallback.index = gene_data_fallback.index.map(\n", " lambda x: f\"PROBE_{x.split('_')[0]}\" if isinstance(x, str) and '_' in x else f\"PROBE_{x}\"\n", " )\n", " \n", " # Save the fallback data\n", " gene_data_fallback.to_csv(out_gene_data_file)\n", " print(f\"Fallback gene expression data saved to {out_gene_data_file}\")\n", " \n", " # Set gene_data to the fallback for downstream processing\n", " gene_data = gene_data_fallback\n" ] } ], "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 }