{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "a099ebda", "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 = \"Depression\"\n", "cohort = \"GSE110298\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Depression\"\n", "in_cohort_dir = \"../../input/GEO/Depression/GSE110298\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Depression/GSE110298.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Depression/gene_data/GSE110298.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Depression/clinical_data/GSE110298.csv\"\n", "json_path = \"../../output/preprocess/Depression/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "aa9a9c30", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "11b2172f", "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": "e0975ad3", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "c5c2784d", "metadata": {}, "outputs": [], "source": [ "I understand the task requires creating and analyzing a clinical dataset from the provided sample characteristics dictionary. Here's my implementation:\n", "\n", "```python\n", "import pandas as pd\n", "import os\n", "import numpy as np\n", "import re\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains microarray data which indicates gene expression\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# For trait (Depression), looking at row 6\n", "trait_row = 6 # Depression scores are available in row 6\n", "\n", "# For age, looking at row 2\n", "age_row = 2 # Age is available in row 2\n", "\n", "# For gender, looking at row 1\n", "gender_row = 1 # Gender is available in row 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert depression value to binary (0/1)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract numerical value after the colon\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " depression_score = int(value)\n", " # Convert to binary: 0 for no depression (score 0), 1 for any depression symptoms (score > 0)\n", " return 0 if depression_score == 0 else 1\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous value\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract numerical value after the colon\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return int(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after the colon\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Initial filtering on the usability of the dataset\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", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create clinical data from the sample characteristics dictionary\n", " # Sample data from the provided dictionary\n", " sample_characteristics = {\n", " 0: ['tissue: hippocampus'], \n", " 1: ['sex (self-reported): female', 'sex (self-reported): male'], \n", " 2: ['age: 89', 'age: 95', 'age: 84', 'age: 76', 'age: 86', 'age: 96', 'age: 80', 'age: 101', 'age: 85', 'age: 92', 'age: 78', 'age: 88', 'age: 81', 'age: 91', 'age: 99', 'age: 79', 'age: 93', 'age: 87'], \n", " 3: ['physical activity tier: low activity', 'physical activity tier: moderate activity', 'physical activity tier: high activity'], \n", " 4: ['physical activity: Actical average counts/day: 1.02', 'physical activity: Actical average counts/day: 0.74', 'physical activity: Actical average counts/day: 1.05', 'physical activity: Actical average counts/day: 0.71', 'physical activity: Actical average counts/day: 0.13', 'physical activity: Actical average counts/day: 1.06', 'physical activity: Actical average counts/day: 0.37', 'physical activity: Actical average counts/day: 0.89', 'physical activity: Actical average counts/day: 0.94', 'physical activity: Actical average counts/day: 0.65', 'physical activity: Actical average counts/day: 0.57', 'physical activity: Actical average counts/day: 1.75', 'physical activity: Actical average counts/day: 2', 'physical activity: Actical average counts/day: 1.48', 'physical activity: Actical average counts/day: 1.72', 'physical activity: Actical average counts/day: 2.06', 'physical activity: Actical average counts/day: 1.4', 'physical activity: Actical average counts/day: 1.8', 'physical activity: Actical average counts/day: 1.99', 'physical activity: Actical average counts/day: 1.87', 'physical activity: Actical average counts/day: 1.44', 'physical activity: Actical average counts/day: 2.32', 'physical activity: Actical average counts/day: 2.6', 'physical activity: Actical average counts/day: 3.53', 'physical activity: Actical average counts/day: 2.82', 'physical activity: Actical average counts/day: 4.19', 'physical activity: Actical average counts/day: 5.6', 'physical activity: Actical average counts/day: 3.26', 'physical activity: Actical average counts/day: 2.99', 'physical activity: Actical average counts/day: 4.7'], \n", " 5: ['education: 10', 'education: 14', 'education: 16', 'education: 12', 'education: 13', 'education: 21', 'education: 11', 'education: 18', 'education: 20', 'education: 15', 'education: 19', 'education: 22'], \n", " 6: ['depression: 0', 'depression: 2', 'depression: 8', 'depression: 1', 'depression: 3', 'depression: 4'], \n", " 7: ['cognitive frequency: 2.429', 'cognitive frequency: 3.143', 'cognitive frequency: 3', 'cognitive frequency: 3.714', 'cognitive frequency: NA', 'cognitive frequency: 1', 'cognitive frequency: 1.14', 'cognitive frequency: 2.29', 'cognitive frequency: 2.57', 'cognitive frequency: 3.57', 'cognitive frequency: 3.71', 'cognitive frequency: 3.571', 'cognitive frequency: 3.86', 'cognitive frequency: 2.71', 'cognitive frequency: 4.29', 'cognitive frequency: 3.429', 'cognitive frequency: 3.857', 'cognitive frequency: 4.143', 'cognitive frequency: 2.286', 'cognitive frequency: 2.86', 'cognitive frequency: 4', 'cognitive frequency: 2.43'], \n", " 8: ['social frequency: 2.167', 'social frequency: 1.333', 'social frequency: 2.333', 'social frequency: 3', 'social frequency: NA', 'social frequency: 1.83', 'social frequency: 2.83', 'social frequency: 2.17', 'social frequency: 1.5', 'social frequency: 2.33', 'social frequency: 2.5', 'social frequency: 1.833', 'social frequency: 2', 'social frequency: 2.67', 'social frequency: 3.167', 'social frequency: 3.333', 'social frequency: 2.667', 'social frequency: 1.67']\n", " }\n", " \n", " # Convert the sample characteristics dictionary to a DataFrame format expected by geo_select_clinical_features\n", " # We want each row to represent a characteristic and each column to represent a sample\n", " # First, determine\n" ] }, { "cell_type": "markdown", "id": "68e5dce7", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "30600a63", "metadata": {}, "outputs": [], "source": [ "# Import necessary libraries\n", "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# Since we don't have output from a previous step, let's first check if the files exist\n", "# before making assumptions about the data\n", "\n", "# Check for matrix file which typically contains sample information\n", "matrix_files = [f for f in os.listdir(in_cohort_dir) if f.endswith(\"_matrix.txt\")]\n", "sample_files = [f for f in os.listdir(in_cohort_dir) if \"sample\" in f.lower() and f.endswith(\".txt\")]\n", "clinical_files = [f for f in os.listdir(in_cohort_dir) if \"clinical\" in f.lower()]\n", "\n", "# Print available files to understand what we're working with\n", "print(f\"Files in {in_cohort_dir}:\")\n", "for file in os.listdir(in_cohort_dir):\n", " print(f\" - {file}\")\n", "\n", "# 1. Determine gene expression data availability\n", "# For GEO datasets, we typically look for series matrix files which contain gene expression data\n", "# Let's check if any files suggest gene expression data\n", "is_gene_available = any(f for f in os.listdir(in_cohort_dir) if \"matrix\" in f.lower() or \"expression\" in f.lower())\n", "print(f\"Gene expression data available: {is_gene_available}\")\n", "\n", "# 2. Variable Availability - Since we don't have sample characteristics data yet, we'll set these to None\n", "# We'll need to analyze the actual data in future steps\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Define conversion functions that will be used if we find the relevant data\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert depression status to binary (0: Control, 1: Depression).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " # Convert to binary\n", " if 'depression' in value or 'mdd' in value or 'case' in value or 'patient' in value:\n", " return 1\n", " elif 'control' in value or 'healthy' in value or 'normal' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"Convert age to float.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " else:\n", " value = value.strip()\n", " \n", " # Try to extract numeric value\n", " try:\n", " # Handle ranges (e.g., \"25-30\") by taking average\n", " if '-' in value:\n", " parts = value.split('-')\n", " return (float(parts[0]) + float(parts[1])) / 2\n", " \n", " # Handle years notation\n", " if 'years' in value or 'y' in value:\n", " return float(value.replace('years', '').replace('y', '').strip())\n", " \n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"Convert gender to binary (0: Female, 1: Male).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " # Convert to binary\n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata with initial filtering\n", "# As we don't have enough information yet, we'll set is_trait_available based on trait_row\n", "is_trait_available = trait_row is not None\n", "print(f\"Trait data available: {is_trait_available}\")\n", "\n", "# Validate and save cohort information with is_final=False for initial validation\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. Skip clinical feature extraction for now since we don't have confirmed data availability\n", "print(\"Clinical feature extraction will be performed in a later step once data availability is confirmed.\")\n" ] }, { "cell_type": "markdown", "id": "1a6d9584", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "c2131edc", "metadata": {}, "outputs": [], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "24032189", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "5bf5e3ce", "metadata": {}, "outputs": [], "source": [ "# Reviewing the gene identifiers\n", "# These identifiers appear to be probe IDs from Affymetrix microarray platform\n", "# Format like \"1007_s_at\" is typical of Affymetrix array probes\n", "# These are not standard human gene symbols (like BRCA1, TP53, etc.)\n", "# Therefore, they need to be mapped to standard gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "0f7dccb2", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "57a5b062", "metadata": {}, "outputs": [], "source": [ "# Get the SOFT and matrix file paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 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. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Look at the columns available and choose the correct ones for mapping\n", "# Based on the columns in the preview, 'ID' is for probe IDs and 'Gene Symbol' contains gene symbols\n", "prob_col = 'ID'\n", "gene_col = 'Gene Symbol'\n", "print(f\"\\nWill use '{prob_col}' for probe IDs and '{gene_col}' for gene symbols in mapping step\")\n", "\n", "# Test extracting mapping data\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"\\nMapping data shape: {mapping_data.shape}\")\n", "print(\"First few rows of mapping data:\")\n", "print(preview_df(mapping_data, n=3))\n" ] }, { "cell_type": "markdown", "id": "1845b87c", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "b2c774a7", "metadata": {}, "outputs": [], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Load the gene expression data again\n", "genetic_data = get_genetic_data(matrix_file)\n", "print(f\"Loaded genetic data with shape: {genetic_data.shape}\")\n", "\n", "# 3. Extract gene annotation data from the SOFT file\n", "gene_annotation = get_gene_annotation(soft_file)\n", "print(f\"Loaded gene annotation data with shape: {gene_annotation.shape}\")\n", "\n", "# 4. Perform gene identifier mapping\n", "print(\"\\nPerforming gene identifier mapping...\")\n", "\n", "# Create mapping from probe IDs to gene symbols\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "print(f\"Created mapping data with shape: {mapping_data.shape}\")\n", "print(f\"Sample of mapping data: {preview_df(mapping_data, n=3)}\")\n", "\n", "# Apply the mapping to convert probe-level measurements to gene-level expression data\n", "gene_data = apply_gene_mapping(expression_df=genetic_data, mapping_df=mapping_data)\n", "print(f\"Transformed gene data shape after mapping: {gene_data.shape}\")\n", "print(\"First 10 gene symbols after mapping:\")\n", "print(gene_data.index[:10])\n", "\n", "# Preview a sample of the mapped gene expression data\n", "gene_sample = gene_data.iloc[:5, :5]\n", "print(\"\\nSample of gene expression data (first 5 genes, first 5 samples):\")\n", "print(gene_sample)\n" ] }, { "cell_type": "markdown", "id": "b8fb2cb4", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "c9abddc7", "metadata": {}, "outputs": [], "source": [ "# 1. Get the SOFT and matrix file paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Re-extract gene expression data and create the gene_data\n", "# Load the gene expression data\n", "genetic_data = get_genetic_data(matrix_file)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "gene_data = apply_gene_mapping(expression_df=genetic_data, mapping_df=mapping_data)\n", "\n", "# Normalize gene symbols in the gene expression data\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n", "\n", "# Save the normalized 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", "\n", "# 2. Re-extract the clinical 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", "# Define conversion functions for clinical features\n", "def convert_trait(value):\n", " \"\"\"Convert depression score to binary format.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " value = value.split(\": \")[-1].strip()\n", " try:\n", " # Depression is measured as a score, converting to binary\n", " # 0 = no depression, 1 = any depression symptoms\n", " depression_score = int(value)\n", " return 0 if depression_score == 0 else 1\n", " except:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous format.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " value = value.split(\": \")[-1].strip()\n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary format (0 for female, 1 for male).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " value = value.split(\": \")[-1].strip().lower()\n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " return None\n", "\n", "# Get clinical data using the identified row indices\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=6, # Depression scores in row 6\n", " convert_trait=convert_trait,\n", " age_row=2, # Age data in row 2\n", " convert_age=convert_age,\n", " gender_row=1, # Gender data in row 1\n", " convert_gender=convert_gender\n", ")\n", "\n", "print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_df))\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)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Linked data is empty\")\n", "\n", "# 3. 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", "# 4. Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Validate and save 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_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from hippocampus samples of elderly subjects with depression scores.\"\n", ")\n", "\n", "# 6. Save the 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 is not usable for analysis. No linked data file saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }