{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "cb86d73c", "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 = \"Obesity\"\n", "cohort = \"GSE84046\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obesity\"\n", "in_cohort_dir = \"../../input/GEO/Obesity/GSE84046\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obesity/GSE84046.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obesity/gene_data/GSE84046.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obesity/clinical_data/GSE84046.csv\"\n", "json_path = \"../../output/preprocess/Obesity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "30c96633", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "bb171714", "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": "cf2688f1", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "7a54af32", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from datetime import datetime\n", "from typing import Optional, Dict, Any, Callable\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this study includes gene expression analysis\n", "# in human adipose tissue, so gene expression data should be available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For the trait (Obesity):\n", "# From the sample characteristics, we can see BMI values at row 6, which can be used to determine obesity\n", "trait_row = 6 # screening bmi (kg/m2) values\n", "\n", "# For gender:\n", "# Gender information is available at row 4 (sexe: Male/Female)\n", "gender_row = 4\n", "\n", "# For age:\n", "# Age is not directly provided, but birth dates are available at row 5\n", "# We could calculate age from birth dates\n", "age_row = 5\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "# Obesity conversion function (using BMI >= 30 as obese)\n", "def convert_trait(value):\n", " try:\n", " if ':' in value:\n", " bmi_value = float(value.split(': ')[1])\n", " # BMI ≥ 30 is considered obese according to standard definition\n", " return 1 if bmi_value >= 30.0 else 0\n", " else:\n", " return None\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "# Age conversion function\n", "def convert_age(value):\n", " try:\n", " if ':' in value:\n", " birth_date_str = value.split(': ')[1]\n", " # Extract year from birth date\n", " birth_year = int(birth_date_str.split('-')[0])\n", " # Since the study was likely conducted around 2017 (based on GEO submission date pattern),\n", " # we'll use this as reference year for age calculation\n", " study_year = 2017 # Approximate study year\n", " age = study_year - birth_year\n", " return age\n", " else:\n", " return None\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "# Gender conversion function\n", "def convert_gender(value):\n", " try:\n", " if ':' in value:\n", " gender = value.split(': ')[1].strip().lower()\n", " if gender == 'female':\n", " return 0\n", " elif gender == 'male':\n", " return 1\n", " else:\n", " return None\n", " else:\n", " return None\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Conduct initial filtering on usability\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=(trait_row is not None)\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " try:\n", " # Make directory for output file if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Extract clinical features using the clinical_data from previous steps\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data, # Use the existing clinical_data from previous steps\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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical data preview:\", preview)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing clinical data: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "30594dc4", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "748b70a5", "metadata": {}, "outputs": [], "source": [ "# 1. First get the file paths again to access the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_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) for future observation\n", "print(\"First 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "4557f8dd", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "1785a863", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers\n", "# These identifiers appear to be microarray probe IDs (numerical IDs) rather than \n", "# human gene symbols which would typically be alphanumeric (like BRCA1, TP53, etc.)\n", "# Standard human gene symbols follow HGNC nomenclature which does not use purely numeric IDs\n", "# These are likely Illumina or Affymetrix microarray probe IDs that need mapping to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "a5e1bd64", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "3aeb38cf", "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. 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": "8c2b0ec2", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "653e52c9", "metadata": {}, "outputs": [], "source": [ "# After analyzing the gene annotation preview, I need to determine which columns \n", "# contain the gene identifier (probe ID) and gene symbols\n", "\n", "# Looking at the data:\n", "# - The 'ID' column in gene_annotation matches the index in gene_data (probe IDs)\n", "# - The 'gene_assignment' column contains gene symbol information we need to extract\n", "\n", "# 1. Create a mapping dataframe using the appropriate columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "\n", "# 2. Apply the gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# 3. Normalize gene symbols to handle synonyms and aggregate by official symbols\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "# 4. Preview the resulting gene expression data\n", "print(\"Gene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First 5 genes:\")\n", "print(gene_data.index[:5])\n", "\n", "# 5. Save the gene expression data to the output 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": "663ed676", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "522a2152", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize the obtained gene data - this was already done in Step 6\n", "# We don't need to redo this normalization\n", "print(f\"Already normalized gene data with shape: {gene_data.shape}\")\n", "\n", "# 2. Load the previously saved clinical data\n", "clinical_data_df = pd.read_csv(out_clinical_data_file)\n", "\n", "# Print clinical data to understand its structure\n", "print(\"Clinical data preview:\")\n", "print(clinical_data_df.head())\n", "\n", "# Set the first column as index if it's not already \n", "if not clinical_data_df.index.name:\n", " clinical_data_df.set_index(clinical_data_df.columns[0], inplace=True)\n", "\n", "# Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_data_df, gene_data)\n", "print(f\"Shape of linked data before missing value handling: {linked_data.shape}\")\n", "\n", "# Print the first few column names to understand what's available\n", "print(\"First columns in linked data:\", list(linked_data.columns)[:10])\n", "\n", "# 3. Handle missing values systematically\n", "# The trait name from the original processing is stored in the columns\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after missing value handling: {linked_data.shape}\")\n", "\n", "# 5. Check if the trait and demographic features are severely biased\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. Validate and save cohort information\n", "note = \"Dataset from protein quantity in energy restriction study with BMI data used for obesity assessment.\"\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_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's 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 is not usable for trait-gene association studies due to quality issues.\")\n" ] }, { "cell_type": "markdown", "id": "52a0f845", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "471e981e", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(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. Extract clinical features using the function from tools.preprocess\n", "# Use the parameters defined in STEP 2 for the trait, age, and gender rows\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", "# Save the extracted clinical features to a CSV file\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 the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Shape of linked data before missing value handling: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values systematically\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after missing value handling: {linked_data.shape}\")\n", "\n", "# 5. Check if the trait and demographic features are severely biased\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. Validate and save cohort information\n", "note = \"Dataset from NAFLD study with hypertension trait information 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=True, \n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's 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 is not usable for trait-gene association studies due to quality issues.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }