{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "a6d07d35", "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 = \"GSE80599\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Parkinsons_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Parkinsons_Disease/GSE80599\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Parkinsons_Disease/GSE80599.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Parkinsons_Disease/gene_data/GSE80599.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Parkinsons_Disease/clinical_data/GSE80599.csv\"\n", "json_path = \"../../output/preprocess/Parkinsons_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "299aeaa6", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "4a841224", "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": "7707333a", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "0718d376", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "import numpy as np\n", "\n", "# 1. Assessment of gene expression data availability\n", "# Based on the background information, this dataset has gene expression data from Affymetrix Human Genome U219 platform\n", "is_gene_available = True\n", "\n", "# 2. Variable availability and data type conversion\n", "\n", "# 2.1 Data Availability\n", "# Trait (Parkinson's Disease progression) is at index 2 in the characteristics dictionary\n", "trait_row = 2\n", "\n", "# Age is at index 4 in the characteristics dictionary\n", "age_row = 4\n", "\n", "# Gender is at index 1 in the characteristics dictionary\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert Parkinson's Disease progression to binary (0=Slow, 1=Rapid)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after the colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if \"slow\" in value.lower():\n", " return 0\n", " elif \"rapid\" in value.lower():\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to a continuous numeric value\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after the colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Extract the numeric part (excluding \"years\" and other text)\n", " import re\n", " age_match = re.search(r'(\\d+)', value)\n", " if age_match:\n", " age = int(age_match.group(1))\n", " # The age 8 might be a data entry error as this is an adult Parkinson's study\n", " if age < 18: # Assuming this is an error\n", " return None\n", " return age\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0=Female, 1=Male)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after the colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save metadata\n", "# 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", " # Load clinical data (assuming it's stored in a CSV or similar format)\n", " # The function assumes clinical_data is a DataFrame where each row is a feature type and columns are samples\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " \n", " # For demonstration, creating a simulated clinical_data DataFrame based on the characteristics dictionary\n", " # In a real scenario, you would load this from a file\n", " clinical_data = pd.DataFrame()\n", " for i, values in {0: ['tissue: whole blood'], \n", " 1: ['gender: Male', 'gender: Female'], \n", " 2: [\"clinical classification: Rapid progression Parkinson's Disease patient\", \n", " \"clinical classification: Slow progression Parkinson's Disease patient\"], \n", " 3: ['updrs-mds3.12 score: 4', 'updrs-mds3.12 score: 3', 'updrs-mds3.12 score: 0', \n", " 'updrs-mds3.12 score: 1', 'updrs-mds3.12 score: 2'], \n", " 4: ['age at examination (years): 68', 'age at examination (years): 58', \n", " 'age at examination (years): 53', 'age at examination (years): 54', \n", " 'age at examination (years): 50', 'age at examination (years): 62']}.items():\n", " for j, value in enumerate(values):\n", " clinical_data.loc[i, f'Sample_{j+1}'] = value\n", " \n", " # Extract clinical features using the geo_select_clinical_features function\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 selected clinical features:\", preview)\n", " \n", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the processed clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "c2ae2a90", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "e05c48fd", "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": "d31818da", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "910a2ece", "metadata": {}, "outputs": [], "source": [ "# These appear to be Affymetrix microarray probe IDs (format: numeric_at or numeric_[x/s]_at)\n", "# rather than standard human gene symbols like \"SNCA\" or \"PARK7\"\n", "# These probe IDs will need to be mapped to their corresponding gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "28baeaf6", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "e976bf56", "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": "6069e6d6", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "4e615a3e", "metadata": {}, "outputs": [], "source": [ "# 1. Determine which columns in gene_annotation contain probe IDs and gene symbols\n", "# From the previous output, we can see:\n", "# - 'ID' column contains probe IDs (like '11715100_at') which match our gene expression data\n", "# - 'Gene Symbol' column contains the human gene symbols (like 'HIST1H3G')\n", "\n", "# 2. Get the gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "print(\"Gene mapping preview (first 5 rows):\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Shape of gene expression data after mapping: {gene_data.shape}\")\n", "print(\"First 5 gene symbols after mapping:\")\n", "print(gene_data.index[:5])\n", "\n", "# Normalize gene symbols to ensure consistency and handle synonyms\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape after normalization: {gene_data.shape}\")\n", "print(\"First 5 normalized gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save the 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": "acc28d73", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "4dc02bbc", "metadata": {}, "outputs": [], "source": [ "# 1. Load the clinical data from the output file\n", "clinical_data_path = out_clinical_data_file\n", "clinical_df = pd.read_csv(clinical_data_path, index_col=0)\n", "print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(clinical_df.head())\n", "\n", "# 2. Load the gene expression data from the output file\n", "gene_data_path = out_gene_data_file\n", "gene_df = pd.read_csv(gene_data_path, index_col=0)\n", "print(f\"Loaded gene expression data with shape: {gene_df.shape}\")\n", "print(f\"First 5 gene symbols: {list(gene_df.index[:5])}\")\n", "\n", "# 3. Link the clinical and genetic data\n", "# Need to examine the sample IDs in both clinical and gene data to ensure proper alignment\n", "print(f\"Clinical data column names (first 5): {list(clinical_df.columns[:5])}\")\n", "print(f\"Gene data column names (first 5): {list(gene_df.columns[:5])}\")\n", "\n", "# Extract GSM IDs from the gene data columns - these should match our clinical samples\n", "# GSM IDs in gene data columns are in format \"GSM2129XXX\"\n", "gene_sample_ids = gene_df.columns.tolist()\n", "\n", "# We need to extract real sample IDs from clinical data to match with gene data\n", "# First check if clinical data has GSM IDs or needs transformation\n", "if clinical_df.shape[1] > 0 and all(col.startswith('Sample_') for col in clinical_df.columns):\n", " print(\"Clinical data has generic sample IDs - need to map to actual GSM IDs\")\n", " \n", " # Re-extract clinical data from the matrix file to get the GSM IDs\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_full = get_background_and_clinical_data(matrix_file)\n", " \n", " # Map sample positions to GSM IDs\n", " sample_id_map = {}\n", " for i, col in enumerate(clinical_full.columns):\n", " if col.startswith('!Sample_geo_accession'):\n", " continue\n", " if i-1 < len(clinical_df.columns): # Skip the first column (GSM IDs)\n", " sample_id_map[clinical_df.columns[i-1]] = clinical_full.iloc[0, i]\n", " \n", " print(f\"Sample ID mapping: {sample_id_map}\")\n", " \n", " # Create new clinical DataFrame with GSM IDs\n", " clinical_gsm_df = pd.DataFrame(index=clinical_df.index)\n", " for sample_id, gsm_id in sample_id_map.items():\n", " if gsm_id in gene_df.columns:\n", " clinical_gsm_df[gsm_id] = clinical_df[sample_id]\n", " \n", " clinical_df = clinical_gsm_df\n", " print(f\"Updated clinical data with GSM IDs, shape: {clinical_df.shape}\")\n", "\n", "# Filter gene data to only include columns that match clinical sample IDs\n", "common_samples = [col for col in gene_df.columns if col in clinical_df.columns]\n", "if not common_samples:\n", " print(\"No matching samples between clinical and gene data!\")\n", " \n", " # Attempt to match using the first 6 samples of the gene data\n", " # (since we know we have 6 clinical samples)\n", " if clinical_df.shape[1] == 6 and gene_df.shape[1] >= 6:\n", " print(\"Attempting to match the first 6 samples...\")\n", " clinical_df.columns = gene_df.columns[:6]\n", " common_samples = gene_df.columns[:6].tolist()\n", "\n", "# After attempting to match samples, link the data\n", "if common_samples:\n", " print(f\"Found {len(common_samples)} common samples between clinical and gene data\")\n", " filtered_gene_df = gene_df[common_samples]\n", " filtered_clinical_df = clinical_df[common_samples]\n", " \n", " # Link the data\n", " linked_data = pd.concat([filtered_clinical_df, filtered_gene_df], axis=0)\n", " linked_data = linked_data.T # Transpose so samples are rows and features are columns\n", " \n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 columns, 5 rows):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values in the linked data\n", " trait_col = filtered_clinical_df.index[0] # Use the first row from clinical data as trait\n", " print(f\"Using '{trait_col}' as the trait column\")\n", " \n", " # Check if we have sufficient trait data\n", " trait_data = linked_data[trait_col].dropna()\n", " print(f\"Non-missing trait values: {len(trait_data)}/{len(linked_data)}\")\n", " \n", " if len(trait_data) >= 10: # Arbitrary threshold - we need enough samples with trait data\n", " handled_data = handle_missing_values(linked_data, trait_col=trait_col)\n", " print(f\"Data shape after handling missing values: {handled_data.shape}\")\n", " \n", " # 5. Determine whether the trait and demographic features are biased\n", " is_biased, handled_data = judge_and_remove_biased_features(handled_data, trait_col)\n", " \n", " # 6. Conduct final quality validation and save relevant 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=len(trait_data) > 0,\n", " is_biased=is_biased,\n", " df=handled_data,\n", " note=\"This dataset contains gene expression profiles from peripheral blood of Parkinson's Disease patients with slow or rapid progression.\"\n", " )\n", " \n", " # 7. If the linked data is usable, save it\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " handled_data.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 biased distribution. Data not saved.\")\n", " else:\n", " print(f\"Insufficient trait data ({len(trait_data)} samples). Dataset cannot be used.\")\n", " \n", " # Record this 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=False,\n", " is_biased=None,\n", " df=linked_data,\n", " note=\"Insufficient trait data to perform analysis.\"\n", " )\n", " print(\"Dataset information recorded, but not saved due to insufficient trait data.\")\n", "else:\n", " print(\"Cannot proceed - no common samples between clinical and gene data\")\n", " \n", " # Record this 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=False,\n", " is_biased=None,\n", " df=pd.DataFrame(),\n", " note=\"Unable to match clinical and gene expression samples.\"\n", " )\n", " print(\"Dataset information recorded, but not saved due to sample matching issues.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }