{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "ad5f6eae", "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 = \"Hepatitis\"\n", "cohort = \"GSE124719\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Hepatitis\"\n", "in_cohort_dir = \"../../input/GEO/Hepatitis/GSE124719\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hepatitis/GSE124719.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hepatitis/gene_data/GSE124719.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hepatitis/clinical_data/GSE124719.csv\"\n", "json_path = \"../../output/preprocess/Hepatitis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "4862c865", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "aff13884", "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": "69dd08d6", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "e4e760fa", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "b1dfdb24", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "1f00b691", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# Let's check what files are available in the input directory\n", "print(f\"Checking contents of {in_cohort_dir}:\")\n", "if os.path.exists(in_cohort_dir):\n", " dir_contents = os.listdir(in_cohort_dir)\n", " print(f\"Files in directory: {dir_contents}\")\n", "else:\n", " print(f\"Directory {in_cohort_dir} does not exist\")\n", "\n", "# Try to load the gene expression data if available\n", "gene_expression_file = os.path.join(in_cohort_dir, \"gene_expression.csv\")\n", "gene_series_file = os.path.join(in_cohort_dir, \"series_matrix.txt\")\n", "\n", "is_gene_available = False\n", "if os.path.exists(gene_expression_file):\n", " print(\"Gene expression file found\")\n", " is_gene_available = True\n", "elif os.path.exists(gene_series_file):\n", " print(\"Series matrix file found, likely contains gene expression data\")\n", " is_gene_available = True\n", "else:\n", " # Check if there are any files that might contain gene expression data\n", " for file in dir_contents if os.path.exists(in_cohort_dir) else []:\n", " if \"gene\" in file.lower() or \"expr\" in file.lower() or \"matrix\" in file.lower():\n", " print(f\"Potential gene expression file found: {file}\")\n", " is_gene_available = True\n", " break\n", "\n", "# Try to load clinical data\n", "clinical_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", "clinical_data = None\n", "if os.path.exists(clinical_file):\n", " clinical_data = pd.read_csv(clinical_file)\n", " print(\"Clinical data preview:\")\n", " print(clinical_data.head())\n", "else:\n", " print(\"Clinical data file not found\")\n", "\n", "# Assuming we don't have direct access to sample characteristics,\n", "# we need to analyze clinical_data to find trait, age, and gender information\n", "\n", "# Set default values\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "is_trait_available = False\n", "\n", "# If clinical data is available, analyze it to identify trait, age, and gender rows\n", "if clinical_data is not None:\n", " # Check column headers to identify potential trait, age, and gender information\n", " for i, column in enumerate(clinical_data.columns):\n", " col_lower = column.lower()\n", " if \"hepatitis\" in col_lower or \"hbv\" in col_lower or \"hcv\" in col_lower or \"disease\" in col_lower or \"status\" in col_lower:\n", " trait_row = i\n", " is_trait_available = True\n", " elif \"age\" in col_lower or \"years\" in col_lower:\n", " age_row = i\n", " elif \"gender\" in col_lower or \"sex\" in col_lower:\n", " gender_row = i\n", " \n", " # Print identified rows\n", " print(f\"Identified rows - Trait: {trait_row}, Age: {age_row}, Gender: {gender_row}\")\n", "\n", "# Define conversion functions for clinical features\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 or 1).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Convert to string to handle both string and numeric values\n", " value_str = str(value).lower()\n", " \n", " # Extract value after colon if present\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " \n", " # Patterns for hepatitis-positive cases\n", " if any(pos_term in value_str for pos_term in [\"positive\", \"hbv\", \"hcv\", \"hepatitis\", \"infected\", \"yes\", \"patient\", \"case\"]):\n", " return 1\n", " # Patterns for hepatitis-negative cases\n", " elif any(neg_term in value_str for neg_term in [\"negative\", \"control\", \"healthy\", \"no\", \"normal\"]):\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Convert to string to handle both string and numeric values\n", " value_str = str(value)\n", " \n", " # Extract value after colon if present\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " \n", " # Try to extract numeric age\n", " import re\n", " age_match = re.search(r'(\\d+\\.?\\d*)', value_str)\n", " if age_match:\n", " return float(age_match.group(1))\n", " else:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Convert to string to handle both string and numeric values\n", " value_str = str(value).lower()\n", " \n", " # Extract value after colon if present\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " \n", " if any(male_term in value_str for male_term in [\"male\", \"m\", \"man\", \"men\"]):\n", " return 1\n", " elif any(female_term in value_str for female_term in [\"female\", \"f\", \"woman\", \"women\"]):\n", " return 0\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Validate and save cohort info (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\n", "if is_trait_available and clinical_data is not None:\n", " # Extract clinical features\n", " clinical_features = 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 features\n", " preview = preview_df(clinical_features)\n", " print(\"\\nExtracted Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Save clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"Trait data not available or clinical data not found. Skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "55f6f9d3", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "a2699841", "metadata": {}, "outputs": [], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "71a68bad", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "665f9d6c", "metadata": {}, "outputs": [], "source": [ "# Based on the gene IDs shown in the output from the previous step, \n", "# they appear to be numeric identifiers (1, 2, 3, etc.) rather than human gene symbols.\n", "# These are likely probe or feature IDs from a microarray platform that need to be \n", "# mapped to actual gene symbols for biological interpretation.\n", "\n", "# In the GEO database, these numeric IDs typically correspond to probes on a microarray,\n", "# and they need to be mapped to gene symbols using platform-specific annotation information.\n", "\n", "requires_gene_mapping = True\n", "print(f\"Based on gene identifier review, mapping requirement: {requires_gene_mapping}\")\n" ] }, { "cell_type": "markdown", "id": "61949527", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "3f80454e", "metadata": {}, "outputs": [], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # First attempt - use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Look for columns that might contain gene symbols\n", " gene_symbol_columns = [col for col in gene_annotation.columns if \n", " any(term in col.lower() for term in ['symbol', 'gene', 'genename', 'gene_symbol'])]\n", " \n", " if gene_symbol_columns:\n", " print(f\"\\nPotential gene symbol columns: {gene_symbol_columns}\")\n", " # Show examples from these columns\n", " for col in gene_symbol_columns:\n", " print(f\"\\nSample values from {col} column:\")\n", " print(gene_annotation[col].dropna().head(10).tolist())\n", " else:\n", " print(\"\\nNo obvious gene symbol columns found. Examining all columns for gene symbol patterns...\")\n", " # Check a few rows of all columns for potential gene symbols\n", " for col in gene_annotation.columns:\n", " sample_values = gene_annotation[col].dropna().head(5).astype(str).tolist()\n", " print(f\"\\nSample values from {col} column: {sample_values}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene annotation data: {e}\")\n", " \n", " # Alternative approach if the library function fails\n", " print(\"\\nTrying alternative approach to find gene annotation...\")\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Look for platform ID\n", " platform_id = None\n", " for line in file:\n", " if line.startswith('!Series_platform_id'):\n", " platform_id = line.split('=')[1].strip()\n", " print(f\"Platform ID: {platform_id}\")\n", " break\n", " \n", " # If we found a platform ID, look for that section\n", " if platform_id:\n", " file.seek(0) # Go back to start of file\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith(f'^PLATFORM = {platform_id}'):\n", " in_platform_section = True\n", " print(f\"Found platform section: {line.strip()}\")\n", " break\n", " \n", " # If we found the platform section, print some annotation info\n", " if in_platform_section:\n", " for i, line in enumerate(file):\n", " if i < 20 and (line.startswith('!Platform_title') or \n", " line.startswith('!Platform_organism') or\n", " line.startswith('!Platform_technology') or\n", " 'annotation' in line.lower()):\n", " print(line.strip())\n" ] }, { "cell_type": "markdown", "id": "4c6a1e3d", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "938a22c2", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the columns in gene annotation for mapping\n", "id_column = 'ID' # The numeric identifiers in gene expression data\n", "gene_symbol_column = 'GENE_SYMBOL' # The standard gene symbols\n", "\n", "print(\"Mapping probe IDs to gene symbols...\")\n", "print(f\"Using {id_column} as probe identifier and {gene_symbol_column} as gene symbol\")\n", "\n", "# 2. Get the gene mapping dataframe \n", "mapping_df = get_gene_mapping(gene_annotation, id_column, gene_symbol_column)\n", "print(f\"Created mapping with {len(mapping_df)} entries\")\n", "print(\"First few mapping entries:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Successfully created gene expression data with {len(gene_data.index)} genes\")\n", "print(\"First few genes in the expression data:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Check shape of the final gene expression data\n", "print(f\"Gene expression data shape: {gene_data.shape}\")\n" ] }, { "cell_type": "markdown", "id": "38d09f30", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "4c1154b4", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols and extract from step 3 and 6\n", "# Load the gene expression data (already loaded from Step 6)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "\n", "try:\n", " # Normalize gene symbols using the NCBI Gene database information\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " \n", " if normalized_gene_data.empty:\n", " print(\"Normalization resulted in empty dataframe. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " \n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data to the output 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 data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " # Save the original gene data if normalization fails\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", "\n", "# 2. Link clinical and genetic data\n", "# Use the trait_row identified in Step 2 (trait_row = 1) to extract trait data\n", "is_trait_available = trait_row is not None\n", "\n", "if is_trait_available:\n", " # Extract clinical features using the function and conversion methods from Step 2\n", " clinical_features = 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", " # Save clinical features\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", "else:\n", " # Create a minimal dataframe with just the trait column\n", " linked_data = pd.DataFrame({trait: [np.nan]})\n", " print(\"No trait data available, creating minimal dataframe for validation.\")\n", "\n", "# 3. Handle missing values in the linked data\n", "if is_trait_available:\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After missing value handling, linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Determine whether trait and demographic features are biased\n", "if is_trait_available and not linked_data.empty and len(linked_data.columns) > 1:\n", " print(\"\\nEvaluating feature bias...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Trait bias evaluation result: {is_biased}\")\n", "else:\n", " is_biased = False\n", " print(\"Skipping bias evaluation due to insufficient data.\")\n", "\n", "# 5. Final validation and save metadata\n", "note = \"\"\n", "if not is_trait_available:\n", " note = f\"Dataset contains gene expression data but no {trait} measurements.\"\n", "elif is_biased:\n", " note = f\"Dataset contains {trait} data but its distribution is severely biased.\"\n", "\n", "# Validate and save cohort info\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available, \n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 6. Save the linked data if usable\n", "print(f\"\\nDataset usability: {is_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(f\"Dataset is not usable for {trait} association studies. Data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }