{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "9ec0b49c", "metadata": {}, "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 = \"GSE49800\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obstructive_sleep_apnea\"\n", "in_cohort_dir = \"../../input/GEO/Obstructive_sleep_apnea/GSE49800\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obstructive_sleep_apnea/GSE49800.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obstructive_sleep_apnea/gene_data/GSE49800.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obstructive_sleep_apnea/clinical_data/GSE49800.csv\"\n", "json_path = \"../../output/preprocess/Obstructive_sleep_apnea/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e12c20b1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "4afd2e51", "metadata": {}, "outputs": [], "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": "4cfb5d10", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "1bd71527", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any, Union\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from leukocytes\n", "# which was hybridized to Affymetrix Genechip Human Gene 1.0 ST microarrays\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability and 2.2 Data Type Conversion\n", "# For trait: The data shows comparison between baseline (no treatment) and CPAP treatment\n", "# This is indicated in row 1 of the sample characteristics\n", "trait_row = 1\n", "\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert OSA treatment information to binary values.\n", " 0: Baseline/no treatment\n", " 1: CPAP treatment\n", " \"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'none' in value or 'baseline' in value:\n", " return 0\n", " elif 'cpap' in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# For age: There's no age information available in the sample characteristics\n", "age_row = None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age information to float values.\n", " Since age data is not available, this function is a placeholder.\n", " \"\"\"\n", " return None\n", "\n", "# For gender: There's no gender information available in the sample characteristics\n", "gender_row = None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender information to binary values.\n", " Since gender data is not available, this function is a placeholder.\n", " \"\"\"\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Trait data is available since trait_row is not None\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, extract clinical features\n", "if trait_row is not None:\n", " # Create a clinical data DataFrame from the sample characteristics dictionary\n", " sample_chars = {\n", " 0: ['subject: 1', 'subject: 2', 'subject: 3', 'subject: 4', 'subject: 5', 'subject: 6', 'subject: 7', \n", " 'subject: 8', 'subject: 9', 'subject: 10', 'subject: 11', 'subject: 12', 'subject: 13', 'subject: 14', \n", " 'subject: 15', 'subject: 16', 'subject: 17', 'subject: 18'],\n", " 1: ['treatment: none, baseline', 'treatment: CPAP']\n", " }\n", " \n", " # Create the clinical DataFrame with proper structure\n", " # Each subject has both baseline and CPAP measurements (total of 36 samples)\n", " data = {}\n", " \n", " for subject in sample_chars[0]:\n", " subject_num = subject.split(\": \")[1]\n", " \n", " # For baseline treatment\n", " sample_id = f\"GSM_{subject_num}_baseline\"\n", " data[sample_id] = [\"treatment: none, baseline\"]\n", " \n", " # For CPAP treatment\n", " sample_id = f\"GSM_{subject_num}_CPAP\" \n", " data[sample_id] = [\"treatment: CPAP\"]\n", " \n", " # Create the clinical DataFrame with proper structure\n", " clinical_data = pd.DataFrame(data)\n", " clinical_data.index = [trait_row] # Set index to trait_row (1)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the dataframe\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Create the output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the selected clinical features to a CSV file\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "302ece1f", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "9312d1ca", "metadata": {}, "outputs": [], "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": "03668df4", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "959c9c20", "metadata": {}, "outputs": [], "source": [ "# Review the gene identifiers\n", "# These appear to be probe IDs (numeric identifiers) from a microarray platform, not human gene symbols\n", "# They are likely Illumina BeadChip probe IDs which need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "32124e37", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "8701d2ed", "metadata": {}, "outputs": [], "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": "c84f7a85", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "b9a723ec", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the columns for probe IDs and gene symbols in the gene annotation data\n", "# Looking at the data, 'ID' contains the probe identifiers (matching the gene expression data index)\n", "# The 'gene_assignment' column contains gene symbol information\n", "\n", "# Create gene mapping dataframe with probe IDs and gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "\n", "# Print information about the mapping dataframe\n", "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n", "print(\"First 5 rows of gene mapping:\")\n", "print(gene_mapping.head())\n", "\n", "# 2. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "# This will split probe values equally among mapped genes and sum values for each gene\n", "gene_expr_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Normalize gene symbols (standardize and handle synonyms)\n", "gene_expr_data = normalize_gene_symbols_in_index(gene_expr_data)\n", "\n", "# Print information about the gene expression data\n", "print(f\"\\nProcessed gene expression data shape: {gene_expr_data.shape}\")\n", "print(\"First 5 gene symbols after mapping:\")\n", "print(gene_expr_data.index[:5])\n", "\n", "# Store the processed gene expression data in gene_data\n", "gene_data = gene_expr_data\n", "\n", "# 3. Save the gene expression data\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\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "11a9a8cb", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "b61cc946", "metadata": {}, "outputs": [], "source": [ "# 1. Properly reference the gene expression data from previous steps\n", "# In the previous step we created gene_expr_data from the mapping operation\n", "# We need to properly reference this variable\n", "gene_data = gene_expr_data\n", "\n", "# 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()}\")\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 using the correct row indices\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Get background information and 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", "# Print clinical data structure to understand available rows\n", "print(\"Clinical data index:\", clinical_data.index.tolist())\n", "print(\"Sample characteristics:\")\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(sample_characteristics_dict)\n", "\n", "# Based on the sample characteristics, we only have 'treatment' information\n", "# No age or gender information is available\n", "trait_row = 1 # Treatment row (baseline vs CPAP)\n", "age_row = None # No age information available\n", "gender_row = None # No gender information available\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert OSA treatment information to binary values.\n", " 0: Baseline/no treatment\n", " 1: CPAP treatment\n", " \"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'none' in value or 'baseline' in value:\n", " return 0\n", " elif 'cpap' in value:\n", " return 1\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=age_row,\n", " convert_age=None,\n", " gender_row=gender_row,\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 - instead of using an undefined function, \n", "# directly use the appropriate judge function\n", "print(\"\\nChecking for bias in the trait variable:\")\n", "trait_type = 'binary' if len(linked_data[trait].unique()) == 2 else 'continuous'\n", "if trait_type == \"binary\":\n", " is_biased = judge_binary_variable_biased(linked_data, trait)\n", "else:\n", " is_biased = judge_continuous_variable_biased(linked_data, trait)\n", "\n", "# 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 (baseline) and after CPAP therapy in patients with severe 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.\")\n" ] }, { "cell_type": "markdown", "id": "c4654c61", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "a0747785", "metadata": {}, "outputs": [], "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", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\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()}\")\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", "# Based on the sample characteristics from previous steps, we only have treatment information\n", "print(\"Clinical data structure:\")\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(sample_characteristics_dict)\n", "\n", "# Use only the treatment information (row 1)\n", "trait_row = 1 # treatment status (baseline vs CPAP)\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 treatment information to binary:\n", " 0: Baseline/no treatment\n", " 1: CPAP treatment\n", " \"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'none' in value or 'baseline' in value:\n", " return 0\n", " elif 'cpap' in value:\n", " return 1\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 (baseline) and after CPAP therapy in patients with severe 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": {}, "nbformat": 4, "nbformat_minor": 5 }