{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "ac16a7e6", "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 = \"GSE135524\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Depression\"\n", "in_cohort_dir = \"../../input/GEO/Depression/GSE135524\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Depression/GSE135524.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Depression/gene_data/GSE135524.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Depression/clinical_data/GSE135524.csv\"\n", "json_path = \"../../output/preprocess/Depression/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "7a644843", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "c4a47f30", "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": "f3290c90", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "da652e54", "metadata": {}, "outputs": [], "source": [ "I'll write code for the current step that fixes the syntax issues and correctly processes the clinical data.\n", "\n", "```python\n", "# 1. Gene Expression Data Availability\n", "# Checking if gene expression data is available based on the background information\n", "# The study seems to involve gene expression analysis in whole blood samples\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# For trait (Depression) - using psychomotor composite score as a proxy for depression severity\n", "trait_row = 7 # psychomotor composite score\n", "\n", "# For age\n", "age_row = 1 # age\n", "\n", "# For gender\n", "gender_row = 2 # Sex\n", "\n", "# 2.2 Data Type Conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert psychomotor composite score to a continuous value.\"\"\"\n", " if value is None or not isinstance(value, str):\n", " return None\n", " # Extract the value after the colon\n", " parts = value.split(':', 1)\n", " if len(parts) < 2:\n", " return None\n", " try:\n", " # Convert to float as it's a continuous measure\n", " return float(parts[1].strip())\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to a continuous value.\"\"\"\n", " if value is None or not isinstance(value, str):\n", " return None\n", " # Extract the value after the colon\n", " parts = value.split(':', 1)\n", " if len(parts) < 2:\n", " return None\n", " try:\n", " # Convert to int as age is typically a whole number\n", " return int(parts[1].strip())\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to a binary value (0 for female, 1 for male).\"\"\"\n", " if value is None or not isinstance(value, str):\n", " return None\n", " # Extract the value after the colon\n", " parts = value.split(':', 1)\n", " if len(parts) < 2:\n", " return None\n", " \n", " gender_value = parts[1].strip().lower()\n", " if 'female' in gender_value:\n", " return 0\n", " elif 'male' in gender_value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability based on trait_row\n", "is_trait_available = trait_row is not None\n", "\n", "# Save cohort info using the provided function\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", "# Only proceed if trait_row is not None\n", "if trait_row is not None:\n", " # Create DataFrame from sample characteristics dictionary\n", " # We'll use the sample characteristics dictionary from the previous step output\n", " sample_characteristics_dict = {\n", " 0: ['individual: Subject 71', 'individual: Subject 73', 'individual: Subject 74', 'individual: Subject 11', \n", " 'individual: Subject 95', 'individual: Subject 41', 'individual: Subject 91', 'individual: Subject 108', \n", " 'individual: Subject 109', 'individual: Subject 86', 'individual: Subject 66', 'individual: Subject 85', \n", " 'individual: Subject 54', 'individual: Subject 20', 'individual: Subject 103', 'individual: Subject 15', \n", " 'individual: Subject 13', 'individual: Subject 46', 'individual: Subject 30', 'individual: Subject 24', \n", " 'individual: Subject 105', 'individual: Subject 48', 'individual: Subject 31', 'individual: Subject 37', \n", " 'individual: Subject 104', 'individual: Subject 114', 'individual: Subject 61', 'individual: Subject 19', \n", " 'individual: Subject 113', 'individual: Subject 110'],\n", " 1: ['age: 55', 'age: 56', 'age: 24', 'age: 61', 'age: 40', 'age: 35', 'age: 41', 'age: 26', 'age: 64', \n", " 'age: 43', 'age: 29', 'age: 34', 'age: 25', 'age: 28', 'age: 27', 'age: 33', 'age: 51', 'age: 52', \n", " 'age: 45', 'age: 42', 'age: 46', 'age: 49', 'age: 38', 'age: 39', 'age: 30', 'age: 32', 'age: 36', \n", " 'age: 22', 'age: 37', 'age: 44'],\n", " 2: ['Sex: Male', 'Sex: Female'],\n", " 3: ['bmi: 24.079', 'bmi: 28.313', 'bmi: 26.549', 'bmi: 25.833', 'bmi: 40.436', 'bmi: 21.658', 'bmi: 52.288', \n", " 'bmi: 43.208', 'bmi: 34.132', 'bmi: 32.029', 'bmi: 32.058', 'bmi: 31.462', 'bmi: 27.924', 'bmi: 44.688', \n", " 'bmi: 38.714', 'bmi: 47.837', 'bmi: 37.67', 'bmi: 27.179', 'bmi: 29.966', 'bmi: 35.833', 'bmi: 24.355', \n", " 'bmi: 48.598', 'bmi: 30.613', 'bmi: 27.653', 'bmi: 28.954', 'bmi: 33.489', 'bmi: 27.836', 'bmi: 39.585', \n", " 'bmi: 30.08', 'bmi: 21.696'],\n", " 4: ['race: White', 'race: Black'],\n", " 5: ['hamd score excluding item 8: 25', 'hamd score excluding item 8: 23', 'hamd score excluding item 8: 21', \n", " 'hamd score excluding item 8: 28', 'hamd score excluding item 8: 24', 'hamd score excluding item 8: 29', \n", " 'hamd score excluding item 8: 22', 'hamd score excluding item 8: 19', 'hamd score excluding item 8: 30', \n", " 'hamd score excluding item 8: 20', 'hamd score excluding item 8: 26', 'hamd score excluding item 8: 27', \n", " 'hamd score excluding item 8: 17', 'hamd score excluding item 8: 18'],\n", " 6: ['college (yes/no): 1', 'college (yes/no): 0'],\n", " 7: ['psychomotor composite score: -0.06308', 'psychomotor composite score: 1.30018', \n", " 'psychomotor composite score: -0.41699', 'psychomotor composite score: -0.17858', \n", " 'psychomotor composite score: -0.64284', 'psychomotor composite score: -0.32956', \n", " 'psychomotor composite score: 0.00218', 'psychomotor composite score: 2.51701', \n", " 'psychomotor composite score: 1.2821', 'psychomotor composite score: 0.18995', \n", " 'psychomotor composite score: -0.40531', 'psychomotor composite score: 0.57381', \n", " 'psychomotor composite score: 0.8438', 'psychomotor composite score: 0.15064', \n", " 'psychomotor composite score: 1.89099', 'psychomotor composite score: 1.03181', \n", " 'psychomotor composite score: -1.73217', 'psychomotor composite score: -0.65832', \n", " 'psychomotor composite score: 0.78252', 'psychomotor composite score: -1.36392', \n", " 'psych\n" ] }, { "cell_type": "markdown", "id": "6b997882", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "046d9daf", "metadata": {}, "outputs": [], "source": [ "I'll provide a properly formatted Python code solution for this step:\n", "\n", "```python\n", "# Let's analyze the dataset by looking at the results of the previous step\n", "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "import gzip\n", "from typing import Callable, Optional, Dict, Any\n", "import re\n", "\n", "# Let's look for the required files in the cohort directory\n", "files = os.listdir(in_cohort_dir)\n", "print(f\"Files in {in_cohort_dir}:\")\n", "for file in files:\n", " print(file)\n", "\n", "# First, let's check if there's a series matrix file which would contain the gene expression data\n", "series_matrix_files = [f for f in files if \"series_matrix\" in f.lower()]\n", "sample_characteristics = {}\n", "\n", "if series_matrix_files:\n", " print(f\"Found series matrix file: {series_matrix_files[0]}\")\n", " matrix_file = os.path.join(in_cohort_dir, series_matrix_files[0])\n", " \n", " # Use gzip to open the compressed file\n", " with gzip.open(matrix_file, 'rt') as f:\n", " # Read header lines to analyze the dataset\n", " header_lines = []\n", " line = f.readline()\n", " while line and not line.startswith('!series_matrix_table_begin'):\n", " header_lines.append(line.strip())\n", " line = f.readline()\n", " \n", " # Extract sample characteristics\n", " sample_chars_lines = [line for line in header_lines if \"!Sample_characteristics_ch1\" in line]\n", " \n", " if sample_chars_lines:\n", " print(\"Sample characteristics found in series matrix file (first 10):\")\n", " for i, line in enumerate(sample_chars_lines[:10]):\n", " print(line.strip())\n", " \n", " # Build a dictionary to store unique values for each characteristic row\n", " for i, line in enumerate(sample_chars_lines):\n", " # Get sample characteristic values\n", " values = re.findall(r'\"([^\"]*)\"', line)\n", " if i not in sample_characteristics:\n", " sample_characteristics[i] = []\n", " sample_characteristics[i].extend(values)\n", " \n", " # Print unique values for each characteristic row to help identify relevant rows\n", " print(\"\\nUnique values for each characteristic row:\")\n", " for row, values in sample_characteristics.items():\n", " unique_values = set(values)\n", " print(f\"Row {row}: {unique_values}\")\n", " \n", " # Check if platform description indicates gene expression data\n", " platform_lines = [line for line in header_lines if \"!Platform_\" in line]\n", " platform_tech_lines = [line for line in platform_lines if \"_technology\" in line.lower() or \"_type\" in line.lower()]\n", " \n", " print(\"\\nPlatform information:\")\n", " for line in platform_tech_lines:\n", " print(line)\n", "\n", "# Based on our analysis of the characteristics rows, let's determine:\n", "# 1. Gene expression data availability\n", "# Assuming it's gene expression data based on platform information\n", "is_gene_available = True # Update this based on actual platform information\n", "\n", "# 2. Trait, age, and gender data availability and row identification\n", "# For now using None as placeholders, we'll update these after analyzing the data\n", "trait_row = None # Row containing depression status\n", "age_row = None # Row containing age information\n", "gender_row = None # Row containing gender information\n", "\n", "# Let's analyze the sample characteristics to determine the correct rows\n", "for row, values in sample_characteristics.items():\n", " unique_values = set(values)\n", " lower_values = [v.lower() if isinstance(v, str) else v for v in unique_values]\n", " \n", " # Check for trait information (depression)\n", " if any((\"depress\" in v or \"mdd\" in v or \"control\" in v or \"patient\" in v or \"case\" in v or \n", " \"healthy\" in v or \"disorder\" in v or \"illness\" in v) for v in lower_values if isinstance(v, str)):\n", " if len(unique_values) > 1: # Ensure it's not a constant feature\n", " trait_row = row\n", " print(f\"Found Depression trait information at row {row}: {unique_values}\")\n", " \n", " # Check for age information\n", " if any((\"age\" in v.lower() or \"years\" in v.lower()) for v in lower_values if isinstance(v, str)):\n", " if len(unique_values) > 1: # Ensure it's not a constant feature\n", " age_row = row\n", " print(f\"Found age information at row {row}: {unique_values}\")\n", " \n", " # Check for gender information\n", " if any((\"gender\" in v.lower() or \"sex\" in v.lower() or \"female\" in v.lower() or \"male\" in v.lower()) \n", " for v in lower_values if isinstance(v, str)):\n", " if len(unique_values) > 1: # Ensure it's not a constant feature\n", " gender_row = row\n", " print(f\"Found gender information at row {row}: {unique_values}\")\n", "\n", "# Define conversion functions based on the actual data patterns\n", "def convert_trait(value):\n", " \"\"\"Convert depression trait value to binary (0: control, 1: case).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = value.lower().strip()\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if any(term in value for term in [\"control\", \"healthy\", \"non-depressed\", \"normal\", \"nd\"]):\n", " return 0\n", " elif any(term in value for term in [\"depressed\", \"mdd\", \"depression\", \"patient\", \"case\"]):\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric value.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract numeric part after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Try to extract numbers from the string\n", " matches = re.findall(r'\\d+(?:\\.\\d+)?', value)\n", " if matches:\n", " try:\n", " age = float(matches[0])\n", " return age\n", " except ValueError:\n", " return None\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0: female, 1: male).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = value.lower().strip()\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if any(term in value for term in [\"female\", \"f\", \"woman\", \"women\"]):\n", " return 0\n", " elif any(term in value for term in [\"male\", \"m\", \"man\", \"men\"]):\n", " return 1\n", " else:\n", " return None\n", "\n", "# Save metadata with 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", "# If clinical data is available, extract and save it\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics\n", " sample_ids = []\n", " \n", " with gzip.open(os.path.join(in_cohort_dir, series_matrix_files[0]), 'rt') as f:\n", " for line in f:\n", " if line.startswith('!Sample_geo_accession'):\n", " sample_ids = re.findall(r'\"([^\"]*)\"', line)\n", " break\n", " \n", " # Create a DataFrame with the correct structure for geo_select_clinical_features\n", " clinical_data = pd.DataFrame(index=range(len(sample_characteristics)), columns=sample_ids)\n", " \n", " for row, values in sample_characteristics.items():\n", " for i, value in enumerate(values):\n", " if i < len(sample_ids):\n", " clinical_data.iloc[row, i] = value\n", " \n", " # Extract clinical features\n", " selected_clinical = 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\n" ] }, { "cell_type": "markdown", "id": "7618eb97", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "21a4847d", "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": "a80ce1f5", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "5fa23c4f", "metadata": {}, "outputs": [], "source": [ "# Analyzing the gene identifiers\n", "\n", "# Based on the observed identifiers (ILMN_XXXXXXX), these are Illumina probe IDs,\n", "# not standard human gene symbols. Illumina probe IDs are platform-specific identifiers\n", "# used in Illumina microarray platforms.\n", "\n", "# These identifiers need to be mapped to standard human gene symbols\n", "# for consistent cross-study analysis and biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "7df4da38", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "ca1967bd", "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", "# Check if there are any platforms defined in the SOFT file that might contain annotation data\n", "with gzip.open(soft_file, 'rt') as f:\n", " soft_content = f.read()\n", "\n", "# Look for platform sections in the SOFT file\n", "platform_sections = re.findall(r'^!Platform_title\\s*=\\s*(.+)$', soft_content, re.MULTILINE)\n", "if platform_sections:\n", " print(f\"Platform title found: {platform_sections[0]}\")\n", "\n", "# Try to extract more annotation data by reading directly from the SOFT file\n", "# Look for lines that might contain gene symbol mappings\n", "symbol_pattern = re.compile(r'ID_REF\\s+Symbol|ID\\s+Gene Symbol', re.IGNORECASE)\n", "annotation_lines = []\n", "with gzip.open(soft_file, 'rt') as f:\n", " for line in f:\n", " if symbol_pattern.search(line):\n", " annotation_lines.append(line)\n", " # Collect the next few lines to see the annotation structure\n", " for _ in range(10):\n", " annotation_lines.append(next(f, ''))\n", "\n", "if annotation_lines:\n", " print(\"Found potential gene symbol mappings:\")\n", " for line in annotation_lines:\n", " print(line.strip())\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"\\nGene annotation preview:\")\n", "print(preview_df(gene_annotation, n=10))\n", "\n", "# If we need an alternative source of mapping, check if there are any other annotation files in the cohort directory\n", "cohort_files = os.listdir(in_cohort_dir)\n", "annotation_files = [f for f in cohort_files if 'annotation' in f.lower() or 'platform' in f.lower()]\n", "if annotation_files:\n", " print(\"\\nAdditional annotation files found in the cohort directory:\")\n", " for file in annotation_files:\n", " print(file)\n" ] }, { "cell_type": "markdown", "id": "779a83fd", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "ba655e58", "metadata": {}, "outputs": [], "source": [ "# 1. Determine which columns in the gene annotation DataFrame contain probe IDs and gene symbols\n", "# Based on the preview, 'ID' column contains probe IDs like ILMN_XXXXXXX, matching the gene_data index\n", "# 'Symbol' column contains gene symbols\n", "\n", "# 2. Extract the probe-to-gene mapping columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"First few rows of the mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# 4. Normalize gene symbols to ensure consistency\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene expression data to a CSV 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": "b11f479a", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "57ff1fdf", "metadata": {}, "outputs": [], "source": [ "# 1. We'll normalize gene symbols in the gene expression data\n", "# Note: We've already done this in step 7, so we can skip this part\n", "\n", "# 2. Link the clinical and genetic data\n", "# First, let's re-acquire the clinical data from the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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", "# Load the normalized gene expression data saved in the previous step\n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "print(f\"Loaded gene expression data shape: {gene_data.shape}\")\n", "\n", "# Define conversion functions for clinical features\n", "def convert_trait(value):\n", " \"\"\"Convert psychomotor composite score to continuous value.\"\"\"\n", " if isinstance(value, str) and \":\" in value:\n", " parts = value.split(\":\", 1)\n", " if len(parts) == 2:\n", " try:\n", " return float(parts[1].strip())\n", " except ValueError:\n", " return None\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to a continuous value.\"\"\"\n", " if isinstance(value, str) and \":\" in value:\n", " parts = value.split(\":\", 1)\n", " if len(parts) == 2:\n", " try:\n", " return int(parts[1].strip())\n", " except ValueError:\n", " return None\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to a binary value (0 for female, 1 for male).\"\"\"\n", " if isinstance(value, str) and \":\" in value:\n", " parts = value.split(\":\", 1)\n", " if len(parts) == 2:\n", " gender_str = parts[1].strip().lower()\n", " if \"female\" in gender_str:\n", " return 0\n", " elif \"male\" in gender_str:\n", " return 1\n", " return None\n", "\n", "# Extract clinical features using the correct rows from the sample characteristics\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=7, # Psychomotor composite score (row 7)\n", " convert_trait=convert_trait,\n", " age_row=1, # Age (row 1)\n", " convert_age=convert_age,\n", " gender_row=2, # Sex (row 2)\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 for future reference\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 whole blood samples of depressed patients with psychomotor slowing traits.\"\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 }