{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "83617e40", "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 = \"Chronic_obstructive_pulmonary_disease_(COPD)\"\n", "cohort = \"GSE162635\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)\"\n", "in_cohort_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE162635\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/GSE162635.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE162635.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE162635.csv\"\n", "json_path = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "17b1a472", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "af79c746", "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": "532a609d", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "30b03bd8", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "from typing import Optional, Callable, Dict, Any\n", "import json\n", "import numpy as np\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from COPD patients\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (COPD status):\n", "# The key 'gold.1' in sample characteristics dictionary indicates GOLD staging for COPD\n", "# GOLD staging is a classification of COPD severity (0 is chronic bronchitis without obstruction,\n", "# I-IV are COPD stages, and healthy indicates control)\n", "trait_row = 2 # corresponds to 'gold.1' values\n", "\n", "# For age:\n", "# Age information is not available in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# For gender:\n", "# Gender information is not available in the sample characteristics dictionary\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "# Convert trait (COPD) function:\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert GOLD staging to binary COPD status\n", " 0 = No COPD (healthy controls)\n", " 1 = COPD (including chronic bronchitis without obstruction and GOLD stages I-IV)\n", " \"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon and strip whitespace\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary COPD status\n", " if value == \"healthy\":\n", " return 0\n", " elif value in [\"O\", \"I\", \"II\", \"III\", \"IV\"]: # All GOLD stages considered COPD\n", " return 1\n", " else:\n", " return None\n", "\n", "# No conversion functions needed for age and gender as they are not available\n", "convert_age = None\n", "convert_gender = None\n", "\n", "# 3. Save Metadata\n", "# Initial filtering on usability\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Load the clinical data\n", " # The data is expected to be in a specific format for geo_select_clinical_features\n", " # We need to construct a DataFrame where rows are features (indexed by numbers)\n", " # and columns are samples\n", " \n", " # Sample characteristics dictionary from previous output\n", " sample_chars_dict = {\n", " 0: ['tissue: transbronchial biopsy'], \n", " 1: ['visit: 1', 'visit: 2', 'visit: 3'], \n", " 2: ['gold.1: O', 'gold.1: II', 'gold.1: III', 'gold.1: I', 'gold.1: healthy', 'gold.1: IV'], \n", " 3: ['gold.2: O', 'gold.2: II', 'gold.2: III', 'gold.2: I', 'phl.1: Productive', 'gold.2: healthy', 'gold.2: IV'], \n", " 4: ['gold.3: O', 'gold.3: II', 'gold.3: III', 'gold.3: I', 'gold.3: IV', 'phl.1: Severe', 'phl.1: No_Dry', 'patid: pat019', 'gold.3: healthy', 'phl.1: Productive', 'patid: pat055'], \n", " 5: ['phl.1: Severe', 'phl.1: Productive', 'phl.1: No_Dry', 'phl.2: Productive', 'phl.2: No_Dry', np.nan, 'phl.1: Healthy', 'phl.2: Severe'], \n", " 6: ['phl.2: Severe', 'phl.2: Productive', 'phl.2: No_Dry', 'patid: pat013', 'patid: pat014', np.nan, 'phl.2: Healthy', 'patid: pat031', 'patid: pat039', 'patid: pat042', 'patid: pat052', 'patid: pat053', 'patid: pat060', 'phl.3: No_Dry'], \n", " 7: ['phl.3: Severe', 'phl.3: No_Dry', 'phl.3: Productive', 'patid: pat010', np.nan, 'phl.3: Healthy', 'patid: pat071'], \n", " 8: ['patid: pat001', 'patid: pat002', 'patid: pat003', 'patid: pat004', 'patid: pat005', 'patid: pat006', 'patid: pat007', 'patid: pat008', 'patid: pat009', np.nan, 'patid: pat011', 'patid: pat012', 'patid: pat015', 'patid: pat016', 'patid: pat017', 'patid: pat018', 'patid: pat020', 'patid: pat021', 'patid: pat022', 'patid: pat023', 'patid: pat024', 'patid: pat025', 'patid: pat026', 'patid: pat027', 'patid: pat028', 'patid: pat029', 'patid: pat030', 'patid: pat032', 'patid: pat033', 'patid: pat034']\n", " }\n", " \n", " # Find the maximum number of samples\n", " max_samples = max(len(values) for values in sample_chars_dict.values())\n", " \n", " # Create sample names\n", " sample_names = [f\"GSM{i+1}\" for i in range(max_samples)]\n", " \n", " # Create a DataFrame with the right structure\n", " clinical_data = pd.DataFrame(index=list(range(max(sample_chars_dict.keys()) + 1)),\n", " columns=sample_names)\n", " \n", " # Fill in the data\n", " for row, values in sample_chars_dict.items():\n", " for i, value in enumerate(values):\n", " if i < len(sample_names): # Make sure we don't go out of bounds\n", " clinical_data.iloc[row, i] = value\n", " \n", " # Extract clinical features\n", " selected_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(selected_features)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\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 extracted features to CSV\n", " selected_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "9e3e8a71", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "38ee48e7", "metadata": {}, "outputs": [], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "7a667009", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "b9629c48", "metadata": {}, "outputs": [], "source": [ "# Review the gene identifiers\n", "# The identifiers (121_at, 1316_at, etc.) appear to be Affymetrix probe IDs from an Affymetrix microarray platform\n", "# These are not human gene symbols but probe identifiers that need to be mapped to gene symbols\n", "# The \"_at\" suffix is characteristic of Affymetrix probe IDs\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "5cb3207b", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "1f189a6d", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Let's look for platform information in the SOFT file to understand the annotation better\n", "print(\"\\nSearching for platform information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if '!Series_platform_id' in line:\n", " print(line.strip())\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Platform ID not found in first 100 lines\")\n", " break\n", "\n", "# Check if the SOFT file includes any reference to gene symbols\n", "print(\"\\nSearching for gene symbol information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " gene_symbol_lines = []\n", " for i, line in enumerate(f):\n", " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n", " gene_symbol_lines.append(line.strip())\n", " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n", " break\n", " \n", " if gene_symbol_lines:\n", " print(\"Found references to gene symbols:\")\n", " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n", " print(line)\n", " else:\n", " print(\"No explicit gene symbol references found in first 1000 lines\")\n", "\n", "# Look for alternative annotation files or references in the directory\n", "print(\"\\nChecking for additional annotation files in the directory:\")\n", "all_files = os.listdir(in_cohort_dir)\n", "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n" ] }, { "cell_type": "markdown", "id": "92f16b0e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "a0c65ce2", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the columns for gene identifier and gene symbol in the annotation\n", "# From the preview, we can see:\n", "# - 'ID' column contains the probe IDs (like \"1007_s_at\") which match the gene expression data row indices\n", "# - 'Gene Symbol' column contains the gene symbols we want to map to\n", "\n", "# 2. Get a gene mapping dataframe\n", "# Use get_gene_mapping to extract the gene identifier and gene symbol columns\n", "# Notice that \"Gene Symbol\" includes multiple genes per probe (e.g., \"DDR1 /// MIR4640\")\n", "prob_col = 'ID'\n", "gene_col = 'Gene Symbol'\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "print(f\"Gene mapping shape: {mapping_data.shape}\")\n", "print(\"Gene mapping sample:\")\n", "print(mapping_data.head())\n", "\n", "# 3. Apply the gene mapping to the gene expression data\n", "# This function will handle probes mapped to multiple genes\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "print(f\"Gene data shape after mapping: {gene_data.shape}\")\n", "print(\"First few gene symbols after mapping:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the mapped 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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "a6355813", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "c93839ab", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene expression 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 expression data saved to {out_gene_data_file}\")\n", "\n", "# 2. Try to load the clinical data if it exists\n", "try:\n", " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Loaded clinical features shape: {clinical_features.shape}\")\n", " has_clinical_data = True\n", "except FileNotFoundError:\n", " print(f\"Clinical data file not found at {out_clinical_data_file}\")\n", " has_clinical_data = False\n", "except pd.errors.EmptyDataError:\n", " print(f\"Clinical data file is empty at {out_clinical_data_file}\")\n", " has_clinical_data = False\n", "\n", "# Link clinical and genetic data if clinical data exists\n", "if has_clinical_data:\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", " \n", " # Check if trait name is in the dataframe index\n", " if trait in linked_data.index:\n", " # 3. Handle missing values\n", " linked_data_clean = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n", " \n", " # 4. Determine whether the trait and demographic features are severely biased\n", " is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n", " trait_available = True\n", " else:\n", " print(f\"Trait '{trait}' not found in linked data. Using first row as placeholder.\")\n", " # Using first row as placeholder for handle_missing_values function\n", " first_row = linked_data.index[0]\n", " linked_data_clean = handle_missing_values(linked_data, first_row)\n", " print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n", " is_biased = True # Mark as biased since no trait information for COPD\n", " trait_available = False\n", "else:\n", " # If no clinical features, just use gene expression data\n", " print(\"No clinical features available, proceeding with gene expression data only\")\n", " linked_data = normalized_gene_data.T # Transpose to match expected format\n", " linked_data_clean = linked_data\n", " is_biased = True # Mark as biased since no trait information\n", " trait_available = False\n", "\n", "# 5. Conduct final quality validation\n", "note = \"Dataset contains gene expression data from transbronchial biopsies from COPD patients at different GOLD stages.\"\n", "if not trait_available:\n", " note += \" No usable COPD trait information for associative analysis.\"\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=trait_available,\n", " is_biased=is_biased,\n", " df=linked_data_clean,\n", " note=note\n", ")\n", "\n", "# 6. Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_clean.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable due to quality issues - linked data not saved\")\n" ] }, { "cell_type": "markdown", "id": "4c65648e", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "a76e25d9", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene expression 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 expression data saved to {out_gene_data_file}\")\n", "\n", "# Use the normalized data for the rest of the analysis\n", "gene_data = normalized_gene_data\n", "\n", "# 2. Since we found out in Step 2 that trait_row is not None, clinical data should be available\n", "try:\n", " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Loaded clinical features shape: {clinical_features.shape}\")\n", " has_clinical_data = True\n", "except (FileNotFoundError, pd.errors.EmptyDataError):\n", " print(f\"Clinical data file not found or empty at {out_clinical_data_file}\")\n", " has_clinical_data = False\n", "\n", "# Create a new DataFrame with a dummy trait column for the purpose of data handling\n", "if has_clinical_data:\n", " # Check if the rows in clinical_features are actually traits\n", " if trait in clinical_features.index:\n", " # Proper clinical data with trait information\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Handle missing values using the trait as the key column\n", " linked_data_clean = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n", " \n", " # Determine whether trait and demographic features are biased\n", " is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n", " trait_available = True\n", " else:\n", " # The clinical data file exists but doesn't have the trait information\n", " print(f\"Trait '{trait}' not found in clinical data.\")\n", " trait_available = False\n", " has_clinical_data = False # Treat as if no clinical data\n", "else:\n", " # No clinical data available\n", " trait_available = False\n", "\n", "# If no proper clinical data with trait, use gene expression data only\n", "if not has_clinical_data:\n", " print(\"No usable clinical features available, proceeding with gene expression data only\")\n", " linked_data = gene_data.T # Transpose to match expected format\n", " linked_data_clean = linked_data\n", " is_biased = True # Mark as biased since no trait information\n", "\n", "# 5. Conduct final quality validation\n", "note = \"Dataset contains gene expression data from transbronchial biopsies from COPD patients at different GOLD stages. \"\n", "if not trait_available:\n", " note += \"No usable COPD trait information for associative analysis.\"\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=trait_available,\n", " is_biased=is_biased if trait_available else True,\n", " df=linked_data_clean,\n", " note=note\n", ")\n", "\n", "# 6. Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_clean.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable due to quality issues - linked data not saved\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }