{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "d1fae3df", "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 = \"GSE181339\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obesity\"\n", "in_cohort_dir = \"../../input/GEO/Obesity/GSE181339\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obesity/GSE181339.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obesity/gene_data/GSE181339.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obesity/clinical_data/GSE181339.csv\"\n", "json_path = \"../../output/preprocess/Obesity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "957a968f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "6de535a2", "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": "d250c211", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "1890a32e", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Dict, Any, Callable, Optional\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series title and summary, this dataset seems to contain gene expression data\n", "# from PBMCs (peripheral blood mononuclear cells)\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Identify keys in the sample characteristics dictionary\n", "# For trait (Obesity): Key 1 contains group classification including 'OW/OB' (overweight/obese)\n", "trait_row = 1\n", "\n", "# For age: Key 2 contains age information\n", "age_row = 2\n", "\n", "# For gender: Key 0 contains gender information \n", "gender_row = 0\n", "\n", "# 2.2 Define conversion functions for each variable\n", "\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert trait value to binary (0 for normal weight, 1 for overweight/obese).\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().upper()\n", " \n", " if 'OW/OB' in value:\n", " return 1 # Overweight/Obese\n", " elif 'NW' in value:\n", " return 0 # Normal Weight\n", " elif 'MONW' in value:\n", " return 0 # Metabolically Obese Normal Weight, but still normal BMI\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age value to continuous number.\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " try:\n", " # Extract the number after the colon\n", " age_str = value.split(':', 1)[1].strip()\n", " return float(age_str)\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male).\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if 'woman' in value or 'female' in value:\n", " return 0\n", " elif 'man' in value or 'male' in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save metadata - perform initial filtering\n", "# Trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\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", "# Since trait_row is not None, proceed with clinical feature extraction\n", "if trait_row is not None:\n", " # Create DataFrame from the sample characteristics dictionary provided in the previous output\n", " sample_characteristics = {\n", " 0: ['gender: Man', 'gender: Woman'], \n", " 1: ['group: NW', 'group: OW/OB', 'group: MONW'], \n", " 2: ['age: 21', 'age: 23', 'age: 10', 'age: 17', 'age: 11', 'age: 1', 'age: 18', 'age: 12', 'age: 8', 'age: 14', 'age: 26', 'age: 4', 'age: 2', 'age: 3', 'age: 7', 'age: 13', 'age: 15', 'age: 9', 'age: 30', 'age: 19'], \n", " 3: ['fasting time: 6hr', 'fasting time: 4hr'], \n", " 4: ['timepoint: 0months', 'timepoint: 6months']\n", " }\n", " \n", " # Convert the dictionary to a DataFrame where each key becomes a row\n", " # First, create a list of series, each representing a row\n", " series_list = [pd.Series(values, name=f\"row_{key}\") for key, values in sample_characteristics.items()]\n", " \n", " # Then concatenate these series into a DataFrame\n", " clinical_data = pd.DataFrame([s.values for s in series_list], index=[s.name for s in series_list])\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 extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\n", " \n", " # Save clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "869c9dfd", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "21b90bf1", "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": "df52bf2f", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "392068da", "metadata": {}, "outputs": [], "source": [ "# These identifiers appear to be numeric values or probe IDs, not human gene symbols\n", "# Human gene symbols typically have letters (like BRCA1, TP53, etc.)\n", "# These numeric identifiers likely need to be mapped to proper gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b96ac91d", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "8fbac43a", "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": "96d69331", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "f1216046", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the columns in the gene annotation dataframe that contain gene identifiers and gene symbols\n", "# Based on the preview, 'ID' column contains identifiers that match the gene expression data's index\n", "# 'GENE_SYMBOL' column contains the actual gene symbols\n", "\n", "# 2. Get a gene mapping dataframe using the get_gene_mapping function\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# This handles the many-to-many relation as specified\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# 4. Print the shape of the resulting gene data and preview some gene symbols to verify mapping\n", "print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n", "print(\"First 20 gene symbols after mapping:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "65ae8ea0", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "0a3bbf43", "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. Load the clinical data that was saved in Step 2\n", "clinical_data_df = pd.read_csv(out_clinical_data_file)\n", "\n", "# Print the column names to understand the structure\n", "print(\"Clinical data columns:\", clinical_data_df.columns.tolist())\n", "print(\"Clinical data preview:\")\n", "print(clinical_data_df.head())\n", "\n", "# Link the clinical and genetic data using the geo_link_clinical_genetic_data function\n", "linked_data = geo_link_clinical_genetic_data(clinical_data_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data columns preview:\", linked_data.columns[:10].tolist())\n", "\n", "# 3. Handle missing values systematically\n", "# Use the actual column number that contains the trait data (column 0 from preview)\n", "linked_data = handle_missing_values(linked_data, '0') # Using '0' instead of trait\n", "print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Determine whether the trait and demographic features are severely biased\n", "# Use the actual column number for the trait\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, '0')\n", "print(f\"Is the trait distribution biased? {is_biased}\")\n", "\n", "# 5. Conduct final quality validation and save relevant information\n", "note = \"Dataset contains normal weight and overweight/obese subjects with gene expression data from PBMCs.\"\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\"Dataset usability status: {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(\"Dataset is not usable for trait-gene association studies.\")\n" ] }, { "cell_type": "markdown", "id": "9d1c1869", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "e0903796", "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", "# Since trait_row is None (as determined in Step 2), we skip the clinical feature extraction\n", "# and data linking steps as instructed.\n", "print(\"No trait data available for this dataset (all subjects have obesity). Skipping clinical feature extraction.\")\n", "\n", "# Create a linked_data DataFrame with only gene expression data for the final validation\n", "# This matches the expected input format for validate_and_save_cohort_info\n", "linked_data = normalized_gene_data.copy()\n", "\n", "# Final validation - mark the dataset as not usable for trait studies\n", "note = \"All subjects in this dataset have obesity, making it unsuitable for obesity vs. non-obesity association studies.\"\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, # False as determined in Step 2\n", " is_biased=True, # No variability in the trait (all have obesity)\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "print(f\"Dataset usability status: {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(\"Dataset is not usable for obesity trait-gene association studies.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }