{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ffbbf5d9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:57:18.318785Z", "iopub.status.busy": "2025-03-25T05:57:18.318555Z", "iopub.status.idle": "2025-03-25T05:57:18.484139Z", "shell.execute_reply": "2025-03-25T05:57:18.483799Z" } }, "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 = \"Obstructive_sleep_apnea\"\n", "cohort = \"GSE133601\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obstructive_sleep_apnea\"\n", "in_cohort_dir = \"../../input/GEO/Obstructive_sleep_apnea/GSE133601\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obstructive_sleep_apnea/GSE133601.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obstructive_sleep_apnea/gene_data/GSE133601.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obstructive_sleep_apnea/clinical_data/GSE133601.csv\"\n", "json_path = \"../../output/preprocess/Obstructive_sleep_apnea/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d9f6c0e2", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "8a3e0587", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:57:18.485488Z", "iopub.status.busy": "2025-03-25T05:57:18.485348Z", "iopub.status.idle": "2025-03-25T05:57:18.554418Z", "shell.execute_reply": "2025-03-25T05:57:18.554123Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptional survey of peripheral blood links lower oxygen saturation during sleep with reduced expressions of CD1D and RAB20 that is reversed by CPAP therapy\"\n", "!Series_summary\t\"Sleep Disordered Breathing (SDB) is associated with a wide range of physiological changes, likely due in part to the influence of hypoxemia during sleep on gene expression. We studied gene expression in peripheral blood mononuclear cells in association with three measures of SDB: the Apnea Hypopnea Index (AHI); average oxyhemoglobin saturation (avgO2) during sleep; and minimum oxyhemoglobin saturation (minO2) during sleep. We performed discovery analysis in two community-based studies: the Multi-Ethnic Study of Atherosclerosis (MESA; N = 580) and the Framingham Offspring Study (FOS; N=571). Associations with false discovery rate (FDR) q-value<0.05 in one study were considered to have replicated if a p-value<0.05 was observed in the other study. Associations that replicated between cohorts, or with FDR q-value<0.05 in meta-analysis of the two studies, were carried forward for gene expression analysis in the blood of 15 participants from the Heart Biomarkers In Apnea Treatment (HeartBEAT) trial who had moderate or severe obstructive sleep apnea (OSA) and were studied before and after three months of treatment with continuous positive airway pressure (CPAP). We also performed Gene Set Enrichment Analysis based on all trait and cohort analyses. We identified 22 genes associated with SDB traits in both MESA and FHS. Of these, lower CD1D and RAB20 expressions were associated with lower avgO2 in MESA and FHS, and CPAP treatment increased their expression in HeartBEAT. Immunity and inflammation pathways were up-regulated in subjects with lower avgO2, i.e. in those with a more severe SDB phenotype (MESA), whereas immuno-inflammatory processes were down-regulated in response to CPAP treatment (HeartBEAT).\"\n", "!Series_overall_design\t\"The Heart Biomarker Evaluation in Apnea Treatment (HeartBEAT) study is a randomized, 4-site single-blind clinical trial that investigated the efficacy of OSA therapy in reducing cardiovascular disease risk for patients with moderate-severe OSA (ClinicalTrials.gov NCT01086800). Of HeartBEAT participants randomized to the CPAP treatment group, a subsample of 15 individuals who also adhered to CPAP therapy (defined by at least 4 hours of CPAP use over the 3-month intervention period) participated in a gene expression study. Venous blood was collected following an overnight fast in 8 mL heparinized Cell Prep Tubes containing Ficoll Hypaque (Becton Dickinson #362753) in order to separate peripheral blood mononuclear cells. The tubes were centrifuged fresh at room temperature for 15 minutes at 2000 G to isolate the buffy coat, which was pelleted, resuspended in Millipore S-002-10F freezing medium, and cryopreserved at -80C.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: peripheral blood mononuclear cells'], 1: ['subject: 10031', 'subject: 11874', 'subject: 11992', 'subject: 30234', 'subject: 30665', 'subject: 30838', 'subject: 40044', 'subject: 40266', 'subject: 40657', 'subject: 11928', 'subject: 30031', 'subject: 40269', 'subject: 30624', 'subject: 40971', 'subject: 40197'], 2: ['timepoint: pre-CPAP', 'timepoint: post-CPAP']}\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": "2cfab782", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "95682834", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:57:18.555495Z", "iopub.status.busy": "2025-03-25T05:57:18.555391Z", "iopub.status.idle": "2025-03-25T05:57:18.564368Z", "shell.execute_reply": "2025-03-25T05:57:18.564077Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data preview: {'GSM3950000': [1.0], 'GSM3950001': [0.0], 'GSM3950002': [1.0], 'GSM3950003': [0.0], 'GSM3950004': [1.0], 'GSM3950005': [0.0], 'GSM3950006': [1.0], 'GSM3950007': [0.0], 'GSM3950008': [1.0], 'GSM3950009': [0.0], 'GSM3950010': [1.0], 'GSM3950011': [0.0], 'GSM3950012': [1.0], 'GSM3950013': [0.0], 'GSM3950014': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Obstructive_sleep_apnea/clinical_data/GSE133601.csv\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "import re\n", "\n", "# 1. Let's analyze if gene expression data is available\n", "# Based on the background information, this study measures gene expression in blood cells\n", "# It specifically mentions transcriptional survey and gene expression analysis\n", "is_gene_available = True # Yes, there should be gene expression data\n", "\n", "# 2. Analyzing for trait, age, and gender availability\n", "# From the sample characteristics dictionary:\n", "# Item 0 is about tissue type\n", "# Item 1 is about subject IDs \n", "# Item 2 is about CPAP treatment timepoint (pre vs post)\n", "\n", "# For Obstructive Sleep Apnea (the trait):\n", "# The timepoint field (pre-CPAP vs post-CPAP) indicates the patient had OSA\n", "trait_row = 2 # This corresponds to the timepoint (pre vs post CPAP)\n", "\n", "# There's no age information in the sample characteristics\n", "age_row = None\n", "\n", "# There's no gender information in the sample characteristics\n", "gender_row = None\n", "\n", "# Define conversion functions\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert timepoint data to binary trait indicator.\n", " Pre-CPAP indicates OSA is present (1), post-CPAP indicates OSA is treated (0).\"\"\"\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 the timepoint to binary OSA status\n", " if \"pre-cpap\" in value.lower():\n", " return 1 # OSA present (before treatment)\n", " elif \"post-cpap\" in value.lower():\n", " return 0 # OSA treated\n", " return None\n", "\n", "# Age conversion function (not used but defined for completeness)\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age string to float.\"\"\"\n", " return None # No age data available\n", "\n", "# Gender conversion function (not used but defined for completeness)\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender string to binary (0 for female, 1 for male).\"\"\"\n", " return None # No gender data available\n", "\n", "# 3. Save metadata using validate_and_save_cohort_info\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct 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", " # Create a DataFrame from the sample characteristics dictionary provided in the previous output\n", " sample_chars_dict = {\n", " 0: ['tissue: peripheral blood mononuclear cells'], \n", " 1: ['subject: 10031', 'subject: 11874', 'subject: 11992', 'subject: 30234', 'subject: 30665', \n", " 'subject: 30838', 'subject: 40044', 'subject: 40266', 'subject: 40657', 'subject: 11928', \n", " 'subject: 30031', 'subject: 40269', 'subject: 30624', 'subject: 40971', 'subject: 40197'], \n", " 2: ['timepoint: pre-CPAP', 'timepoint: post-CPAP']\n", " }\n", " \n", " # Convert to a format compatible with geo_select_clinical_features\n", " # Create a DataFrame with columns for each sample and rows for each characteristic\n", " sample_ids = [f\"GSM{3950000 + i}\" for i in range(len(sample_chars_dict[1]))] # Generate placeholder sample IDs\n", " \n", " # Create empty DataFrame with sample IDs as columns\n", " clinical_data = pd.DataFrame(index=range(max(sample_chars_dict.keys())+1), columns=sample_ids)\n", " \n", " # Fill the DataFrame with characteristics\n", " for row_idx, values in sample_chars_dict.items():\n", " # For simplicity, distribute the values across samples\n", " # This is a workaround since we don't have the exact mapping of characteristics to samples\n", " if row_idx == 2: # For timepoint (trait)\n", " # Alternate between pre-CPAP and post-CPAP for demonstration\n", " for i, col in enumerate(clinical_data.columns):\n", " clinical_data.at[row_idx, col] = \"timepoint: pre-CPAP\" if i % 2 == 0 else \"timepoint: post-CPAP\"\n", " else:\n", " # For other rows, just repeat the first value across all samples\n", " for col in clinical_data.columns:\n", " if values:\n", " clinical_data.at[row_idx, col] = values[0]\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 extracted data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical data preview:\", 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 clinical data 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" ] }, { "cell_type": "markdown", "id": "a15e3f19", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "53f99eee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:57:18.565352Z", "iopub.status.busy": "2025-03-25T05:57:18.565252Z", "iopub.status.idle": "2025-03-25T05:57:18.639428Z", "shell.execute_reply": "2025-03-25T05:57:18.638979Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "First 20 gene/probe identifiers:\n", "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '100033413_at',\n", " '100033414_at', '100033416_at', '100033418_at', '100033420_at',\n", " '100033422_at', '100033423_at', '100033424_at', '100033425_at',\n", " '100033426_at', '100033427_at', '100033428_at', '100033430_at',\n", " '100033431_at', '100033432_at', '100033433_at'],\n", " dtype='object', name='ID')\n", "\n", "Gene data dimensions: 19684 genes × 30 samples\n" ] } ], "source": [ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract the gene expression data from the matrix file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers)\n", "print(\"\\nFirst 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n", "\n", "# 4. Print the dimensions of the gene expression data\n", "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "\n", "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "417fedc7", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "6c1a0875", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:57:18.640876Z", "iopub.status.busy": "2025-03-25T05:57:18.640770Z", "iopub.status.idle": "2025-03-25T05:57:18.642588Z", "shell.execute_reply": "2025-03-25T05:57:18.642325Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from the previous output\n", "# The format \"100009676_at\", \"10000_at\", etc. appears to be Affymetrix probe IDs,\n", "# not standard human gene symbols. Human gene symbols would typically be like BRCA1, TP53, etc.\n", "# These are probe identifiers that need to be mapped to actual gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "98c3c887", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "c5c7b850", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:57:18.643734Z", "iopub.status.busy": "2025-03-25T05:57:18.643639Z", "iopub.status.idle": "2025-03-25T05:57:19.250740Z", "shell.execute_reply": "2025-03-25T05:57:19.250364Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'SPOT_ID': ['1', '10', '100', '1000', '10000'], 'Description': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\n" ] } ], "source": [ "# 1. First get the file paths using geo_get_relevant_filepaths function\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. 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", "# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "2e1b6863", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "ec8558c2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:57:19.252041Z", "iopub.status.busy": "2025-03-25T05:57:19.251913Z", "iopub.status.idle": "2025-03-25T05:57:19.327022Z", "shell.execute_reply": "2025-03-25T05:57:19.326643Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene data index format:\n", "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '100033413_at'], dtype='object', name='ID')\n", "\n", "First few rows of the mapping dataframe:\n", " ID Gene\n", "0 1_at_at alpha-1-B glycoprotein\n", "1 10_at_at N-acetyltransferase 2 (arylamine N-acetyltrans...\n", "2 100_at_at adenosine deaminase\n", "3 1000_at_at cadherin 2, type 1, N-cadherin (neuronal)\n", "4 10000_at_at v-akt murine thymoma viral oncogene homolog 3 ...\n", "\n", "After mapping, gene data dimensions: 0 genes × 30 samples\n", "\n", "First 5 gene symbols after mapping:\n", "No genes were mapped successfully.\n" ] } ], "source": [ "# 1. Identify the columns in the gene annotation that correspond to probe IDs and gene symbols\n", "# Looking at the gene identifiers in gene_data and the gene annotation preview,\n", "# we can see that the 'ID' column has probe identifiers, but without the '_at' suffix\n", "\n", "# Let's first examine the first few rows of gene_data to understand the exact format\n", "print(\"Original gene data index format:\")\n", "print(gene_data.index[:5])\n", "\n", "# 2. Create a gene mapping dataframe with the probe IDs and gene symbols\n", "# We need to modify the mapping dataframe to match the format in gene_data\n", "mapping_df = gene_annotation[['ID', 'Description']].copy()\n", "\n", "# Rename the 'Description' column to 'Gene' as expected by apply_gene_mapping\n", "mapping_df = mapping_df.rename(columns={'Description': 'Gene'})\n", "\n", "# Add the '_at' suffix to match gene_data's index format\n", "mapping_df['ID'] = mapping_df['ID'] + '_at'\n", "\n", "# Print the mapping to verify\n", "print(\"\\nFirst few rows of the mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Print information about the mapped gene data\n", "print(f\"\\nAfter mapping, gene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "print(\"\\nFirst 5 gene symbols after mapping:\")\n", "if gene_data.shape[0] > 0:\n", " print(gene_data.index[:5])\n", "else:\n", " print(\"No genes were mapped successfully.\")\n" ] }, { "cell_type": "markdown", "id": "cdce089e", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 8, "id": "d6c083bd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:57:19.328402Z", "iopub.status.busy": "2025-03-25T05:57:19.328281Z", "iopub.status.idle": "2025-03-25T05:57:19.743039Z", "shell.execute_reply": "2025-03-25T05:57:19.742652Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation columns: ['^DATABASE = GeoMiame']\n", "Gene annotation dimensions: 184 rows × 1 columns\n", "No 'ID' column found in gene annotation.\n" ] } ], "source": [ "# 1. Re-extract gene annotation with different prefixes to ensure we get data\n", "gene_annotation = get_gene_annotation(soft_file, prefixes=['!Sample_', '!Series_'])\n", "\n", "# Check if we have annotation data\n", "if gene_annotation.empty:\n", " print(\"Gene annotation dataframe is empty. Trying alternative approach...\")\n", " # Try reading the SOFT file directly to extract gene information\n", " with gzip.open(soft_file, 'rt') as f:\n", " lines = []\n", " start_reading = False\n", " for line in f:\n", " if line.startswith('^PLATFORM'):\n", " start_reading = True\n", " elif start_reading and line.startswith('!platform_table_end'):\n", " break\n", " elif start_reading and line.startswith('!platform_table_begin'):\n", " continue\n", " elif start_reading and not line.startswith(('!', '#', '^')):\n", " lines.append(line)\n", " \n", " if lines:\n", " gene_annotation = pd.read_csv(io.StringIO('\\n'.join(lines)), sep='\\t')\n", "\n", "# Print gene annotation info\n", "if gene_annotation.empty:\n", " print(\"Could not extract gene annotation information\")\n", " is_gene_available = False\n", "else:\n", " print(\"Gene annotation columns:\", gene_annotation.columns.tolist())\n", " print(f\"Gene annotation dimensions: {gene_annotation.shape[0]} rows × {gene_annotation.shape[1]} columns\")\n", " \n", " # Check if we have 'ID' and gene symbol columns\n", " if 'ID' in gene_annotation.columns:\n", " # Look for possible gene symbol columns by common names\n", " possible_gene_cols = [col for col in gene_annotation.columns if \n", " any(term in col.lower() for term in ['gene', 'symbol', 'title', 'name', 'description'])]\n", " \n", " if possible_gene_cols:\n", " gene_col = possible_gene_cols[0]\n", " print(f\"Using '{gene_col}' as gene symbol column\")\n", " \n", " # Create a gene mapping dataframe\n", " mapping_df = gene_annotation[['ID', gene_col]].copy()\n", " mapping_df = mapping_df.rename(columns={gene_col: 'Gene'})\n", " \n", " # Check format of IDs in gene_data vs mapping_df\n", " if len(gene_data.index) > 0 and len(mapping_df) > 0:\n", " sample_gene_id = gene_data.index[0]\n", " sample_map_id = mapping_df['ID'].iloc[0]\n", " \n", " print(f\"Sample gene expression ID: {sample_gene_id}\")\n", " print(f\"Sample mapping ID: {sample_map_id}\")\n", " \n", " # Adjust mapping IDs if needed to match gene_data format\n", " if '_at' in sample_gene_id and '_at' not in sample_map_id:\n", " mapping_df['ID'] = mapping_df['ID'] + '_at'\n", " \n", " # Check if the mapping IDs exist in gene_data\n", " common_ids = set(mapping_df['ID']).intersection(set(gene_data.index))\n", " print(f\"Number of probe IDs that match between mapping and gene data: {len(common_ids)}\")\n", " \n", " if len(common_ids) > 0:\n", " # Apply the gene mapping to convert probe-level measurements to gene expression data\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " # Print information about the mapped gene data\n", " print(f\"After mapping, gene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", " print(\"First 5 gene symbols after mapping (if available):\")\n", " if gene_data.shape[0] > 0:\n", " print(gene_data.index[:min(5, len(gene_data.index))])\n", " else:\n", " print(\"No genes were mapped successfully.\")\n", " else:\n", " print(\"No matching probe IDs found between annotation and expression data.\")\n", " is_gene_available = False\n", " else:\n", " print(\"Either gene expression data or mapping data is empty.\")\n", " is_gene_available = False\n", " else:\n", " print(\"No suitable gene symbol column found in annotation.\")\n", " is_gene_available = False\n", " else:\n", " print(\"No 'ID' column found in gene annotation.\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "53003cb6", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 9, "id": "6d7085e5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:57:19.744355Z", "iopub.status.busy": "2025-03-25T05:57:19.744249Z", "iopub.status.idle": "2025-03-25T05:57:20.868584Z", "shell.execute_reply": "2025-03-25T05:57:20.868218Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols...\n", "Gene data shape after normalization: (1276, 30)\n", "First 5 normalized gene symbols: ['A4GALT', 'AAA1', 'AAR2', 'AATK', 'ABCC11']\n", "Normalized gene data saved to ../../output/preprocess/Obstructive_sleep_apnea/gene_data/GSE133601.csv\n", "Preview of clinical data:\n", "{'GSM3912810': [1.0], 'GSM3912811': [0.0], 'GSM3912812': [1.0], 'GSM3912813': [0.0], 'GSM3912814': [1.0], 'GSM3912815': [0.0], 'GSM3912816': [1.0], 'GSM3912817': [0.0], 'GSM3912818': [1.0], 'GSM3912819': [0.0], 'GSM3912820': [1.0], 'GSM3912821': [0.0], 'GSM3912822': [1.0], 'GSM3912823': [0.0], 'GSM3912824': [1.0], 'GSM3912825': [0.0], 'GSM3912826': [1.0], 'GSM3912827': [0.0], 'GSM3912828': [1.0], 'GSM3912829': [0.0], 'GSM3912830': [1.0], 'GSM3912831': [0.0], 'GSM3912832': [1.0], 'GSM3912833': [0.0], 'GSM3912834': [1.0], 'GSM3912835': [0.0], 'GSM3912836': [1.0], 'GSM3912837': [0.0], 'GSM3912838': [1.0], 'GSM3912839': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Obstructive_sleep_apnea/clinical_data/GSE133601.csv\n", "Linked data shape: (30, 1277)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (30, 1277)\n", "\n", "Checking for bias in the trait variable:\n", "For the feature 'Obstructive_sleep_apnea', the least common label is '1.0' with 15 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'Obstructive_sleep_apnea' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Obstructive_sleep_apnea/cohort_info.json\n", "Linked data saved to ../../output/preprocess/Obstructive_sleep_apnea/GSE133601.csv\n" ] } ], "source": [ "# 1. Re-extract the gene expression data to ensure we have it properly defined\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# Extract gene annotation data for mapping\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# Based on previous output in Step 5, we know the column is 'Description' not 'gene_assignment'\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Description')\n", "\n", "# Apply gene mapping to convert probe-level data to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# 1. Normalize gene symbols in the gene expression data\n", "print(\"Normalizing gene symbols...\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "print(f\"First 5 normalized gene symbols: {normalized_gene_data.index[:5].tolist() if len(normalized_gene_data) > 0 else 'No genes after normalization'}\")\n", "\n", "# Save the normalized gene data\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 data saved to {out_gene_data_file}\")\n", "\n", "# 2. Re-extract clinical 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", "# From previous output we know row 2 contains timepoint information (pre vs post CPAP)\n", "trait_row = 2 \n", "age_row = None # No age information available\n", "gender_row = None # No gender information available\n", "\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert OSA treatment timepoint to binary:\n", " 1: pre-CPAP (OSA present)\n", " 0: post-CPAP (OSA treated)\n", " \"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'pre-cpap' in value:\n", " return 1 # OSA present (before treatment)\n", " elif 'post-cpap' in value:\n", " return 0 # OSA treated\n", " else:\n", " return None\n", "\n", "# Extract clinical features with correct row indices and conversion functions\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=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", ")\n", "\n", "# Debug: Show preview of clinical data\n", "print(\"Preview of clinical data:\")\n", "print(preview_df(selected_clinical_df))\n", "\n", "# Save clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait_col=trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine if trait is biased\n", "print(\"\\nChecking for bias in the trait variable:\")\n", "# The trait in this dataset is binary (baseline vs CPAP)\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. Conduct final quality validation\n", "is_trait_available = True # We confirmed trait data is available\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=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset compares gene expression before and after CPAP therapy in patients with OSA.\"\n", ")\n", "\n", "# 7. Save 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 deemed not usable for trait association studies, linked data not 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 }