{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "32d0ee3e", "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 = \"Parkinsons_Disease\"\n", "cohort = \"GSE202667\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Parkinsons_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Parkinsons_Disease/GSE202667\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Parkinsons_Disease/GSE202667.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Parkinsons_Disease/gene_data/GSE202667.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Parkinsons_Disease/clinical_data/GSE202667.csv\"\n", "json_path = \"../../output/preprocess/Parkinsons_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "628c56a7", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "ab7e4eb9", "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": "88321542", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "c3de838a", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import re\n", "import numpy as np\n", "from typing import Optional, Dict, Any, List, Callable\n", "\n", "# Determine data availability\n", "is_gene_available = True # Dataset likely contains gene expression data based on CD4+ T cells examination\n", "\n", "# Find appropriate keys for trait, age, and gender\n", "trait_row = 0 # \"disease state\" provides information about Parkinson's disease vs control\n", "age_row = 3 # Contains age information with values like \"age: 53\"\n", "gender_row = 2 # Contains gender information, though all appear to be male\n", "\n", "# Define conversion functions for each variable\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert trait value to binary: 1 for PD, 0 for control.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Convert to string if it's not already\n", " value = str(value)\n", " \n", " # Extract the value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if re.search(r\"parkinson|pd\", value.lower()):\n", " return 1\n", " elif re.search(r\"healthy|control|hc\", value.lower()):\n", " return 0\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age value to continuous numeric value.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Convert to string if it's not already\n", " value = str(value)\n", " \n", " # Extract the value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Extract numeric value\n", " match = re.search(r'(\\d+)', value)\n", " if match:\n", " return float(match.group(1))\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 pd.isna(value):\n", " return None\n", " \n", " # Convert to string if it's not already\n", " value = str(value)\n", " \n", " # Extract the value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if re.search(r\"male\", value.lower()):\n", " return 1\n", " elif re.search(r\"female\", value.lower()):\n", " return 0\n", " return None\n", "\n", "# Validate and save cohort info for initial filtering\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", "# Proceed with clinical feature extraction if trait data is available\n", "if trait_row is not None:\n", " # Sample characteristics dictionary\n", " sample_chars = {\n", " 0: [\"disease state: Parkinson's disease\", 'disease state: Healthy Control'], \n", " 1: ['cell type: CD4+ T cells'], \n", " 2: ['gender: male'], \n", " 3: ['age: 53', 'age: 57', 'age: 63', 'age: 75', 'age: 85', 'age: 76', 'age: 69', 'age: 66'], \n", " 4: ['Stage: 1', 'Stage: 0 (Healthy Control)', 'Stage: 4', 'Stage: 2.5'], \n", " 5: ['time-point post activation: 0 h', 'time-point post activation: 2 h', 'time-point post activation: 4 h', \n", " 'time-point post activation: 8 h', 'time-point post activation: 12 h', 'time-point post activation: 24 h']\n", " }\n", " \n", " # Transpose the data to create a DataFrame with samples as columns\n", " # This matches the expected structure for geo_select_clinical_features\n", " sample_ids = [f'GSM{6000000+i}' for i in range(max(len(v) for v in sample_chars.values()))]\n", " clinical_data = pd.DataFrame(index=sample_chars.keys(), columns=sample_ids)\n", " \n", " for row_idx, values in sample_chars.items():\n", " for col_idx, value in enumerate(values):\n", " if col_idx < len(clinical_data.columns):\n", " clinical_data.at[row_idx, clinical_data.columns[col_idx]] = value\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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of Selected Clinical Features:\")\n", " print(preview)\n", " \n", " # Save clinical data\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": "9af681d1", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "c7c4b381", "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": "886b9b56", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "4e4c3a67", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers\n", "# These are numeric identifiers (1, 2, 3, etc.) which are not standard human gene symbols\n", "# Standard human gene symbols are alphanumeric like SNCA, PARK2, LRRK2, etc.\n", "# These are likely probe IDs that need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "0685a879", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "fd6f7268", "metadata": {}, "outputs": [], "source": [ "# 1. First get the file paths using geo_get_relevant_filepaths function\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. 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", "# 3. 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": "79859383", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "163cc4b9", "metadata": {}, "outputs": [], "source": [ "# 1. Observe and decide which columns to use for mapping\n", "# The gene expression data uses numeric IDs like '1', '2', '3' as seen in the previous step\n", "# From the gene annotation preview, we need to map the 'ID' column to 'GENE_SYMBOL' column\n", "\n", "# 2. Extract the mapping between gene identifiers and gene symbols \n", "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "\n", "print(\"Gene mapping preview (first 10 rows):\")\n", "print(mapping_data.head(10))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "\n", "print(f\"Shape of gene expression data after mapping: {gene_data.shape}\")\n", "print(\"First 10 genes after mapping:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "dcd559e2", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "3f8c41f2", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols from the already mapped gene expression data from Step 6\n", "# Apply normalization to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene expression data shape after normalization: {normalized_gene_data.shape}\")\n", "print(\"First 5 normalized gene symbols:\")\n", "print(normalized_gene_data.index[:5])\n", "\n", "# Save the normalized 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 already processed in Step 2\n", "if os.path.exists(out_clinical_data_file):\n", " clinical_data_processed = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(\"Loaded clinical data from file\")\n", "else:\n", " # If the file wasn't saved, recreate the clinical features using the same parameters as in Step 2\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Define the conversion functions from Step 2\n", " def convert_trait(value: str) -> Optional[int]:\n", " if pd.isna(value):\n", " return None\n", " value = str(value)\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " if re.search(r\"parkinson|pd\", value.lower()):\n", " return 1\n", " elif re.search(r\"healthy|control|hc\", value.lower()):\n", " return 0\n", " return None\n", "\n", " def convert_age(value: str) -> Optional[float]:\n", " if pd.isna(value):\n", " return None\n", " value = str(value)\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " match = re.search(r'(\\d+)', value)\n", " if match:\n", " return float(match.group(1))\n", " return None\n", "\n", " def convert_gender(value: str) -> Optional[int]:\n", " if pd.isna(value):\n", " return None\n", " value = str(value)\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " if re.search(r\"male\", value.lower()):\n", " return 1\n", " elif re.search(r\"female\", value.lower()):\n", " return 0\n", " return None\n", " \n", " clinical_data_processed = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0, # From Step 2\n", " convert_trait=convert_trait,\n", " age_row=3, # From Step 2\n", " convert_age=convert_age,\n", " gender_row=2, # From Step 2\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Save it\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_data_processed.to_csv(out_clinical_data_file)\n", "\n", "# Ensure proper structure of clinical data\n", "if isinstance(clinical_data_processed.index, pd.RangeIndex):\n", " # If index is numeric range, fix the structure\n", " clinical_data_processed.index = [trait, 'Age', 'Gender']\n", "\n", "print(\"Clinical data shape:\", clinical_data_processed.shape)\n", "print(\"Clinical data preview:\")\n", "print(preview_df(clinical_data_processed))\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_data_processed, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data columns (first 5):\", linked_data.columns[:5])\n", "\n", "# Print some statistics before handling missing values\n", "print(f\"Missing values per column (first 5): {linked_data.isna().sum().head()}\")\n", "print(f\"Missing values in trait column: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", "\n", "# 4. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine if trait and demographic features are biased\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", "print(f\"Is the trait biased: {is_biased}\")\n", "\n", "# 6. 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=True,\n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from CD4+ T cells comparing PD patients to healthy controls.\"\n", ")\n", "\n", "# 7. Save linked data if 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 deemed not usable. Linked data was not saved.\")\n" ] }, { "cell_type": "markdown", "id": "60c68432", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "ce4f372d", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols from the already mapped gene expression data from Step 6\n", "# Apply normalization to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene expression data shape after normalization: {normalized_gene_data.shape}\")\n", "print(\"First 5 normalized gene symbols:\")\n", "print(normalized_gene_data.index[:5])\n", "\n", "# Save the normalized 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 already processed in Step 2\n", "# We need to load the clinical data from the file that was saved in Step 2\n", "if os.path.exists(out_clinical_data_file):\n", " clinical_data_processed = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(\"Loaded clinical data from file\")\n", "else:\n", " # If for some reason the file wasn't saved, recreate the clinical features using the same parameters as in Step 2\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Use the same conversion function and trait_row from Step 2\n", " def convert_trait(value):\n", " \"\"\"Convert occupation to binary trait (exposure risk for Parkinson's)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = value.lower().split(\": \")[-1].strip()\n", " \n", " if \"farmworker\" in value:\n", " return 1 # Higher pesticide exposure (risk factor for Parkinson's)\n", " elif \"manual worker\" in value:\n", " return 0 # Lower pesticide exposure \n", " else:\n", " return None\n", " \n", " # Use the exact same parameters as we determined in Step 2\n", " clinical_data_processed = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0, # From Step 2\n", " convert_trait=convert_trait,\n", " age_row=None, # From Step 2\n", " convert_age=None,\n", " gender_row=None, # From Step 2\n", " convert_gender=None\n", " )\n", " \n", " # Save it again just to be sure\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_data_processed.to_csv(out_clinical_data_file)\n", "\n", "print(\"Clinical data shape:\", clinical_data_processed.shape)\n", "print(\"Clinical data preview:\")\n", "print(preview_df(clinical_data_processed))\n", "\n", "# 3. Link clinical and genetic data\n", "# The clinical data is oriented with genes/traits as rows and samples as columns\n", "# Transpose the normalized gene data to match this orientation (samples as columns)\n", "genetic_data_t = normalized_gene_data\n", "\n", "# Link clinical and genetic data vertically\n", "linked_data = geo_link_clinical_genetic_data(clinical_data_processed, genetic_data_t)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine if trait and demographic features are biased\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", "print(f\"Is the trait biased: {is_biased}\")\n", "\n", "# 6. 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=True,\n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from blood samples comparing farmworkers (with higher pesticide exposure, a risk factor for Parkinson's) to manual workers.\"\n", ")\n", "\n", "# 7. Save linked data if 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 deemed not usable. Linked data was not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }