{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "6dafb34b", "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 = \"Vitamin_D_Levels\"\n", "cohort = \"GSE76324\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Vitamin_D_Levels\"\n", "in_cohort_dir = \"../../input/GEO/Vitamin_D_Levels/GSE76324\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Vitamin_D_Levels/GSE76324.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Vitamin_D_Levels/gene_data/GSE76324.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Vitamin_D_Levels/clinical_data/GSE76324.csv\"\n", "json_path = \"../../output/preprocess/Vitamin_D_Levels/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "b1ce330b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "73a4810e", "metadata": {}, "outputs": [], "source": [ "# 1. Let's first list the directory contents to understand what files are available\n", "import os\n", "\n", "print(\"Files in the cohort directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Adapt file identification to handle different naming patterns\n", "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n", "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n", "\n", "# If no files with these patterns are found, look for alternative file types\n", "if not soft_files:\n", " soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "if not matrix_files:\n", " matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "\n", "print(\"Identified SOFT files:\", soft_files)\n", "print(\"Identified matrix files:\", matrix_files)\n", "\n", "# Use the first files found, if any\n", "if len(soft_files) > 0 and len(matrix_files) > 0:\n", " soft_file = os.path.join(in_cohort_dir, soft_files[0])\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n", " print(background_info)\n", " print(\"\\nSample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", "else:\n", " print(\"No appropriate files found in the directory.\")\n" ] }, { "cell_type": "markdown", "id": "672b5435", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "69b8b511", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# 1. Determine if gene expression data is available\n", "# Based on background information, this is a microarray study of airway epithelium\n", "# and mentions gene expression analysis, so we can assume gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Trait (Vitamin D Levels)\n", "# Looking at the Sample Characteristics Dictionary, row 3 seems to contain vitamin D level data\n", "trait_row = 3 # Serum 25-OH-D levels are in row 3\n", "\n", "# Function to convert vitamin D levels\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " if \"low vitamin d\" in value:\n", " return 0 # Low vitamin D levels\n", " elif \"mid vitamin d\" in value:\n", " return 1 # Mid vitamin D levels\n", " elif \"high vitamin d\" in value:\n", " return 2 # High vitamin D levels\n", " else:\n", " return None\n", "\n", "# 2.2 Age\n", "# Age information is not provided in the sample characteristics dictionary\n", "age_row = None\n", "\n", "def convert_age(value):\n", " return None # Not applicable as age data is not available\n", "\n", "# 2.3 Gender\n", "# Gender information is not provided in the sample characteristics dictionary\n", "gender_row = None\n", "\n", "def convert_gender(value):\n", " return None # Not applicable as gender data is not available\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\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", "# Only proceed if trait_row is not None\n", "if trait_row is not None:\n", " # Create a clinical data DataFrame from the GEO data\n", " # We need to use the get_feature_data function which is implicitly imported\n", " # since it's used within geo_select_clinical_features\n", " \n", " # First, load the clinical data from the matrix file\n", " # The function geo_select_clinical_features will handle the parsing\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"GSE76324_series_matrix.txt.gz\"), \n", " sep='\\t', compression='gzip', comment='!')\n", " \n", " # Extract clinical features using the provided utility function\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 dataframe\n", " preview = preview_df(clinical_features)\n", " print(\"Preview of 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 the clinical features as CSV\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "ede687d5", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "96f31929", "metadata": {}, "outputs": [], "source": [ "# Use the helper function to get the proper file paths\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "try:\n", " gene_data = get_genetic_data(matrix_file_path)\n", " \n", " # Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", " \n", " # Print shape to understand the dataset dimensions\n", " print(f\"\\nGene expression data shape: {gene_data.shape}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "fda059bb", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "b209eaca", "metadata": {}, "outputs": [], "source": [ "# Gene Identifier Review\n", "# Looking at the gene identifiers like '1007_s_at', '1053_at', '117_at', etc.\n", "# These appear to be Affymetrix probe IDs, not human gene symbols\n", "# Affymetrix microarray probe IDs need to be mapped to human gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "8c72c8d0", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "a42e1e21", "metadata": {}, "outputs": [], "source": [ "# 1. This part examines the data more thoroughly to determine what type of data it contains\n", "try:\n", " # First, let's check a few rows of the gene_data we extracted in Step 3\n", " print(\"Sample of gene expression data (first 5 rows, first 5 columns):\")\n", " print(gene_data.iloc[:5, :5])\n", " \n", " # Analyze the SOFT file to identify the data type and mapping information\n", " platform_info = []\n", " with gzip.open(soft_file_path, 'rt', encoding='latin-1') as f:\n", " for line in f:\n", " if line.startswith(\"!Platform_title\") or line.startswith(\"!Series_title\") or \"description\" in line.lower():\n", " platform_info.append(line.strip())\n", " \n", " print(\"\\nPlatform information:\")\n", " for line in platform_info:\n", " print(line)\n", " \n", " # Extract the gene annotation using the library function\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # Display column names of the annotation dataframe\n", " print(\"\\nGene annotation columns:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Preview the annotation dataframe\n", " print(\"\\nGene annotation preview:\")\n", " annotation_preview = preview_df(gene_annotation)\n", " print(annotation_preview)\n", " \n", " # Check if ID column exists in the gene_annotation dataframe\n", " if 'ID' in gene_annotation.columns:\n", " # Check if any of the IDs in gene_annotation match those in gene_data\n", " sample_ids = list(gene_data.index[:10])\n", " matching_rows = gene_annotation[gene_annotation['ID'].isin(sample_ids)]\n", " print(f\"\\nMatching rows in annotation for sample IDs: {len(matching_rows)}\")\n", " \n", " # Look for gene symbol column\n", " gene_symbol_candidates = [col for col in gene_annotation.columns if 'gene' in col.lower() or 'symbol' in col.lower() or 'name' in col.lower()]\n", " print(f\"\\nPotential gene symbol columns: {gene_symbol_candidates}\")\n", " \n", "except Exception as e:\n", " print(f\"Error analyzing gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n", "\n", "# Based on our analysis, determine if this is really gene expression data\n", "# Check the platform description and match with the data we've extracted\n", "is_gene_expression = False\n", "for info in platform_info:\n", " if 'expression' in info.lower() or 'transcript' in info.lower() or 'mrna' in info.lower():\n", " is_gene_expression = True\n", " break\n", "\n", "print(f\"\\nIs this dataset likely to contain gene expression data? {is_gene_expression}\")\n", "\n", "# If this isn't gene expression data, we need to update our metadata\n", "if not is_gene_expression:\n", " print(\"\\nNOTE: Based on our analysis, this dataset doesn't appear to contain gene expression data.\")\n", " print(\"It appears to be a different type of data (possibly SNP array or other genomic data).\")\n", " # Update is_gene_available for metadata\n", " is_gene_available = False\n", " \n", " # Save the updated metadata\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" ] }, { "cell_type": "markdown", "id": "52a80bd2", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "d39cb8d4", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the appropriate columns for gene mapping\n", "print(\"Examining gene mapping potential columns...\")\n", "\n", "# From the previous step, we see that:\n", "# - The gene expression data's index contains probe IDs like '1007_s_at'\n", "# - The gene annotation dataframe has a column 'ID' that matches these probe IDs\n", "# - The 'Gene Symbol' column contains the actual gene symbols we want\n", "\n", "# 2. Get gene mapping dataframe\n", "prob_col = 'ID' # This is the column containing probe IDs\n", "gene_col = 'Gene Symbol' # This column contains gene symbols\n", "\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\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", "# 3. Apply gene mapping to convert probe data to gene data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First 10 gene symbols after mapping:\")\n", "print(gene_data.index[:10])\n", "\n", "# Normalize gene symbols (handle synonyms)\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n", "print(\"First 10 normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene data to file\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": "b4cd7f1b", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "3974c87c", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "# Note: We already normalized gene symbols in the previous step, so we can skip this part\n", "\n", "# 2. Load the clinical data\n", "try:\n", " # First check what our clinical data actually contains\n", " background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", " clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", " \n", " # Get the matrix file path again\n", " _, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Re-extract the background info and clinical data\n", " background_info, clinical_df = get_background_and_clinical_data(matrix_file_path, background_prefixes, clinical_prefixes)\n", " \n", " # Create a dictionary of unique values for each row to see what we're working with\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_df)\n", " print(\"Sample characteristics dictionary:\")\n", " print(sample_characteristics_dict)\n", " \n", " # Extract the vitamin D levels data\n", " if trait_row is not None:\n", " # Re-create the clinical features\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_df,\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", " print(\"Recreated clinical features:\")\n", " print(clinical_features)\n", " \n", " # Make sure clinical features are properly formatted\n", " if clinical_features.shape[0] > 0:\n", " # If we have rows with feature names, transpose to get samples as rows\n", " clinical_data = clinical_features.T\n", " if trait not in clinical_data.columns:\n", " # Rename the column to our trait name\n", " clinical_data = clinical_data.rename(columns={clinical_data.columns[0]: trait})\n", " print(\"Clinical data after processing:\")\n", " print(clinical_data.head())\n", " else:\n", " print(\"No clinical features extracted, creating default data\")\n", " # Create default data\n", " clinical_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " clinical_data[trait] = 0 # Default value as fallback\n", " else:\n", " print(\"No trait row identified, creating default clinical data\")\n", " clinical_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " clinical_data[trait] = 0 # Default value\n", "except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " # Create a minimal dataset as fallback\n", " clinical_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " clinical_data[trait] = 0 # Default value\n", "\n", "# 3. Link clinical and genetic data\n", "# Make sure gene data is formatted with genes as rows and samples as columns\n", "if normalized_gene_data.index.name != 'Gene':\n", " normalized_gene_data.index.name = 'Gene'\n", "\n", "# Transpose gene data to have samples as rows and genes as columns\n", "gene_data_for_linking = normalized_gene_data.T\n", "print(f\"Gene data shape for linking (samples as rows): {gene_data_for_linking.shape}\")\n", "\n", "# Make sure clinical_data has the same index format as gene_data_for_linking\n", "clinical_data.index = clinical_data.index.astype(str)\n", "gene_data_for_linking.index = gene_data_for_linking.index.astype(str)\n", "\n", "# Find common samples\n", "common_samples = set(clinical_data.index) & set(gene_data_for_linking.index)\n", "print(f\"Number of common samples between clinical and genetic data: {len(common_samples)}\")\n", "\n", "# Filter to common samples\n", "clinical_data = clinical_data.loc[clinical_data.index.isin(common_samples)]\n", "gene_data_for_linking = gene_data_for_linking.loc[gene_data_for_linking.index.isin(common_samples)]\n", "\n", "# Now link by concatenating horizontally\n", "linked_data = pd.concat([clinical_data, gene_data_for_linking], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data trait values distribution:\")\n", "print(linked_data[trait].value_counts())\n", "\n", "# 4. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# Check if we still have data\n", "if linked_data.shape[0] == 0 or linked_data.shape[1] <= 1:\n", " print(\"WARNING: No samples or features left after handling missing values.\")\n", " is_trait_biased = True\n", " note = \"Dataset failed preprocessing: No samples left after handling missing values.\"\n", "else:\n", " # 5. Determine whether the trait and demographic features are biased\n", " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Is trait biased: {is_trait_biased}\")\n", " note = \"This dataset contains gene expression data from airway epithelium, with vitamin D levels categorized as low, mid, and high.\"\n", "\n", "# 6. Conduct quality check and save the cohort information\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=True,\n", " is_biased=is_trait_biased, \n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n", "if is_usable:\n", " # Create directory if it doesn't exist\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\"Data not saved due to quality issues.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }