{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "1a92f989", "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 = \"Intellectual_Disability\"\n", "cohort = \"GSE59630\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Intellectual_Disability\"\n", "in_cohort_dir = \"../../input/GEO/Intellectual_Disability/GSE59630\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Intellectual_Disability/GSE59630.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Intellectual_Disability/gene_data/GSE59630.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Intellectual_Disability/clinical_data/GSE59630.csv\"\n", "json_path = \"../../output/preprocess/Intellectual_Disability/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "5fb2da15", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "a2dc6449", "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": "f504da40", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "2181a652", "metadata": {}, "outputs": [], "source": [ "```python\n", "# 1. Check gene expression data availability\n", "# This dataset is about gene expression in the brain, as mentioned in the background information\n", "is_gene_available = True\n", "\n", "# 2. Variable availability and data type conversion\n", "# 2.1 Data Availability\n", "\n", "# Intellectual Disability is represented as Down Syndrome (DS) in this dataset\n", "# Found in key 2: 'disease status: CTL', 'disease status: DS'\n", "trait_row = 2 \n", "\n", "# Age information is in key 4\n", "age_row = 4 \n", "\n", "# Gender information is in key 3: 'Sex: F', 'Sex: M'\n", "gender_row = 3 \n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait value (Down Syndrome status) to binary (0 for control, 1 for DS)\"\"\"\n", " if value is None:\n", " return None\n", " # Extract the value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'DS':\n", " return 1\n", " elif value.upper() == 'CTL':\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to a numeric value in years\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Extract numeric part and unit\n", " import re\n", " match = re.match(r'(\\d+)(\\w+)', value)\n", " if not match:\n", " return None\n", " \n", " number, unit = match.groups()\n", " number = float(number)\n", " \n", " # Convert to years based on unit\n", " if unit == 'yr':\n", " return number\n", " elif unit == 'mo':\n", " return number / 12\n", " elif unit == 'wg': # weeks of gestation\n", " return number / 52 # approximate conversion to years\n", " \n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'F':\n", " return 0\n", " elif value.upper() == 'M':\n", " return 1\n", " \n", " return None\n", "\n", "# 3. Save Metadata\n", "# Since trait_row is not None, trait data is available\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 (if trait_row is not None)\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary\n", " sample_chars = {\n", " 0: ['braincode: 97-DFC', 'braincode: 100-DFC', 'braincode: 100-V1C', 'braincode: 159-V1C', 'braincode: 132-DFC', 'braincode: 132-V1C', 'braincode: 132-CBC', 'braincode: 131-OFC', 'braincode: 131-DFC', 'braincode: 131-VFC', 'braincode: 131-ITC', 'braincode: 131-V1C', 'braincode: 131-HIP', 'braincode: 131-CBC', 'braincode: 171-DFC', 'braincode: 171-VFC', 'braincode: 171-MFC', 'braincode: 171-OFC', 'braincode: 171-S1C', 'braincode: 171-IPC', 'braincode: 171-STC', 'braincode: 171-ITC', 'braincode: 171-V1C', 'braincode: 171-CBC', 'braincode: 122-V1C', 'braincode: 122-CBC', 'braincode: 143-OFC', 'braincode: 143-DFC', 'braincode: 173-VFC', 'braincode: 173-ITC'], \n", " 1: ['region: DFC', 'region: V1C', 'region: CBC', 'region: OFC', 'region: VFC', 'region: ITC', 'region: HIP', 'region: MFC', 'region: S1C', 'region: IPC', 'region: STC', 'region: FC'], \n", " 2: ['disease status: CTL', 'disease status: DS'], \n", " 3: ['Sex: F', 'Sex: M'], \n", " 4: ['age: 17wg', 'age: 19wg', 'age: 22wg', 'age: 4mo', 'age: 6mo', 'age: 10mo', 'age: 12mo', 'age: 2yr', 'age: 3yr', 'age: 8yr', 'age: 15yr', 'age: 18yr', 'age: 22yr', 'age: 30yr', 'age: 42yr', 'age: 16wg', 'age: 1mo', 'age: 9mo', 'age: 14mo', 'age: 10yr', 'age: 13yr', 'age: 19yr', 'age: 39yr', 'age: 40yr'], \n", " 5: ['Stage: 5', 'Stage: 6', 'Stage: 8', 'Stage: 9', 'Stage: 10', 'Stage: 11', 'Stage: 12', 'Stage: 13', 'Stage: 14'], \n", " 6: ['postmortem interval: 2', 'postmortem interval: 4', 'postmortem interval: 1', 'postmortem interval: 22', 'postmortem interval: 26', 'postmortem interval: 18', 'postmortem interval: 12', 'postmortem interval: 8', 'postmortem interval: 16', 'postmortem interval: 14.5', 'postmortem interval: 28', 'postmortem interval: 9.5', 'postmortem interval: 19', 'postmortem interval: 3', 'postmortem interval: 23', 'postmortem interval: 24', 'postmortem interval: 11', 'postmortem interval: 17', 'postmortem interval: 15', 'postmortem interval: 10'], \n", " 7: ['race: CC', 'race: AA', 'race: H'], \n", " 8: ['rna integrity number: 8.9', 'rna integrity number: 10', 'rna integrity number: 7.6', 'rna integrity number: 9.5', 'rna integrity number: 9.2', 'rna integrity number: 7', 'rna integrity number: 7.1', 'rna integrity number: 7.5', 'rna integrity number: 7.4', 'rna integrity number: 8.4', 'rna integrity number: 8.6', 'rna integrity number: 8.8', 'rna integrity number: 8.7', 'rna integrity number: 9.4', 'rna integrity number: 9', 'rna integrity number: 9.6', 'rna integrity number: 9.8', 'rna integrity number: 5', 'rna integrity number: 7.2', 'rna integrity number: 8', 'rna integrity number: 7.8', 'rna integrity number: 9.7', 'rna integrity number: 8.1', 'rna integrity number: 7.9', 'rna integrity number: 9.3', '\n" ] }, { "cell_type": "markdown", "id": "78589f2a", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "9648663a", "metadata": {}, "outputs": [], "source": [ "```python\n", "import pandas as pd\n", "import json\n", "import os\n", "import re\n", "from typing import Optional, Callable, Dict, Any, List\n", "\n", "# First, examine what files are available in the cohort directory\n", "print(f\"Examining directory: {in_cohort_dir}\")\n", "if os.path.exists(in_cohort_dir):\n", " directory_contents = os.listdir(in_cohort_dir)\n", " print(f\"Files in directory: {directory_contents}\")\n", "else:\n", " print(f\"Directory {in_cohort_dir} does not exist\")\n", " directory_contents = []\n", "\n", "# Check for available data files\n", "series_matrix_files = [f for f in directory_contents if \"series_matrix\" in f.lower()]\n", "soft_files = [f for f in directory_contents if f.lower().endswith(\".soft\") or f.lower().endswith(\".soft.gz\")]\n", "json_files = [f for f in directory_contents if f.lower().endswith(\".json\")]\n", "\n", "# Load clinical data from available files\n", "clinical_data_dict = {}\n", "sample_characteristics = {}\n", "\n", "# Try to load clinical data from different possible file formats\n", "if json_files and any(\"clinical_data\" in f.lower() for f in json_files):\n", " clinical_json = next(f for f in json_files if \"clinical_data\" in f.lower())\n", " clinical_data_path = os.path.join(in_cohort_dir, clinical_json)\n", " try:\n", " with open(clinical_data_path, 'r') as f:\n", " clinical_data_dict = json.load(f)\n", " sample_characteristics = clinical_data_dict.get(\"sample_characteristics\", {})\n", " print(f\"Loaded clinical data from {clinical_json}\")\n", " except Exception as e:\n", " print(f\"Error loading {clinical_json}: {str(e)}\")\n", "elif series_matrix_files:\n", " # We would need to parse series matrix file to extract clinical data\n", " print(\"Series matrix files found but need additional parsing\")\n", " # Placeholder for series matrix parsing\n", " is_gene_available = True\n", " is_trait_available = False\n", "elif soft_files:\n", " # We would need to parse soft file to extract clinical data\n", " print(\"SOFT files found but need additional parsing\")\n", " # Placeholder for SOFT file parsing\n", " is_gene_available = True\n", " is_trait_available = False\n", "else:\n", " print(\"No recognizable clinical data files found\")\n", " is_gene_available = False\n", " is_trait_available = False\n", "\n", "# If we have sample characteristics, analyze them\n", "if sample_characteristics:\n", " print(\"Sample characteristics keys:\")\n", " for key in sample_characteristics.keys():\n", " print(f\"Key {key}: {sample_characteristics[key]}\")\n", "\n", " # Determine if gene expression data is available\n", " platform_id = clinical_data_dict.get(\"platform_id\", \"\")\n", " title = clinical_data_dict.get(\"title\", \"\")\n", " summary = clinical_data_dict.get(\"summary\", \"\")\n", "\n", " is_gene_available = True\n", " if any(term in platform_id.lower() or term in title.lower() or term in summary.lower() \n", " for term in [\"mirna\", \"methylation\", \"methyl\"]):\n", " if not any(term in platform_id.lower() or term in title.lower() or term in summary.lower() \n", " for term in [\"gene expression\", \"transcriptome\", \"mrna\"]):\n", " is_gene_available = False\n", "\n", " # Identify the row in sample characteristics containing trait information\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", "\n", " # Check each key in sample characteristics for trait, age, and gender data\n", " for key, values in sample_characteristics.items():\n", " unique_values = set(values)\n", " \n", " # Check for intellectual disability information\n", " if any(\"intellectual\" in str(v).lower() for v in unique_values) or \\\n", " any(\"disability\" in str(v).lower() for v in unique_values) or \\\n", " any(\"id\" in str(v).lower() and \"patient\" in str(v).lower() for v in unique_values) or \\\n", " any(\"control\" in str(v).lower() for v in unique_values):\n", " if len(unique_values) > 1: # Ensure it's not a constant feature\n", " trait_row = int(key)\n", " \n", " # Check for age information\n", " if any(\"age\" in str(v).lower() for v in unique_values):\n", " if len(unique_values) > 1: # Ensure it's not a constant feature\n", " age_row = int(key)\n", " \n", " # Check for gender information\n", " if any(\"gender\" in str(v).lower() for v in unique_values) or \\\n", " any(\"sex\" in str(v).lower() for v in unique_values) or \\\n", " any(\"male\" in str(v).lower() for v in unique_values) or \\\n", " any(\"female\" in str(v).lower() for v in unique_values):\n", " if len(unique_values) > 1: # Ensure it's not a constant feature\n", " gender_row = int(key)\n", "\n", " # Define conversion functions\n", " def convert_trait(value):\n", " \"\"\"Convert trait values to binary (0: control, 1: intellectual disability).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " value_lower = str(value).lower()\n", " \n", " # Extract content after colon if present\n", " if \":\" in value_lower:\n", " value_lower = value_lower.split(\":\", 1)[1].strip()\n", " \n", " if any(term in value_lower for term in [\"patient\", \"case\", \"intellectual disability\", \"id patient\"]):\n", " return 1\n", " elif any(term in value_lower for term in [\"control\", \"healthy\", \"normal\"]):\n", " return 0\n", " \n", " return None\n", "\n", " def convert_age(value):\n", " \"\"\"Convert age values to continuous numeric values.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " value_str = str(value)\n", " \n", " # Extract content after colon if present\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " \n", " # Try to extract numeric age using regex\n", " age_match = re.search(r'(\\d+(?:\\.\\d+)?)', value_str)\n", " if age_match:\n", " return float(age_match.group(1))\n", " \n", " return None\n", "\n", " def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0: female, 1: male).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " value_lower = str(value).lower()\n", " \n", " # Extract content after colon if present\n", " if \":\" in value_lower:\n", " value_lower = value_lower.split(\":\", 1)[1].strip()\n", " \n", " if any(term in value_lower for term in [\"female\", \"f\", \"woman\"]):\n", " return 0\n", " elif any(term in value_lower for term in [\"male\", \"m\", \"man\"]):\n", " return 1\n", " \n", " return None\n", "\n", " # Check trait data availability\n", " is_trait_available = trait_row is not None\n", "else:\n", " # If no sample characteristics data is found, set variables to default values\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", " is_trait_available = False\n", "\n", "# Print found information\n", "print(f\"Gene expression data available: {is_gene_available}\")\n", "print(f\"Trait data available: {is_trait_available}\")\n", "if is_trait_available:\n", " print(f\"Trait row: {trait_row}\")\n", " print(f\"Age row: {age_row}\")\n", " print(f\"Gender row: {gender_row}\")\n", "\n", "# Save metadata with initial filtering\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", "# Extract clinical features if trait data is available\n", "if is_trait_available and sample_characteristics:\n", " # Convert sample characteristics dictionary to DataFrame for processing\n", " clinical_df = pd.DataFrame.from_dict(sample_characteristics, orient='index')\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_df,\n", " trait=trait,\n", " trait_row=trait_row,\n" ] }, { "cell_type": "markdown", "id": "bb461be2", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "4a9ceeab", "metadata": {}, "outputs": [], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "74cd122a", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "3403bd70", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers from the output\n", "# These appear to be Affymetrix probe IDs, not standard human gene symbols\n", "# These numeric IDs (2315554, 2315633, etc.) need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "18e572b2", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "215ec1cc", "metadata": {}, "outputs": [], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "18dd18ce", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "55ba939a", "metadata": {}, "outputs": [], "source": [ "# 1. Identifying mapping columns in the gene annotation data\n", "print(\"Examining gene annotation data to identify mapping columns...\")\n", "\n", "# The 'ID' column in gene_annotation contains probe IDs matching the gene expression data indices\n", "# The 'gene_assignment' column contains gene symbol information, but needs parsing\n", "\n", "# Examining the gene_assignment column\n", "print(\"\\nExample gene_assignment values:\")\n", "print(gene_annotation['gene_assignment'].head(3).tolist())\n", "\n", "# 2. Create a mapping dataframe with probe IDs and gene symbols\n", "print(\"\\nCreating gene mapping dataframe...\")\n", "\n", "# Function to extract gene symbols from gene_assignment string\n", "def extract_gene_symbols(assignment):\n", " if isinstance(assignment, str) and assignment != '---':\n", " # Extract gene symbols that appear after '//' (typically the second element after splitting by '//')\n", " parts = assignment.split('//')\n", " if len(parts) >= 2:\n", " gene_symbol = parts[1].strip()\n", " return gene_symbol\n", " return None\n", "\n", "# Apply extraction to create mapping\n", "gene_annotation['Gene'] = gene_annotation['gene_assignment'].apply(extract_gene_symbols)\n", "\n", "# Create mapping dataframe with ID and Gene columns\n", "mapping_df = gene_annotation[['ID', 'Gene']].copy()\n", "mapping_df = mapping_df.dropna() # Remove rows without gene symbols\n", "print(f\"Created mapping with {len(mapping_df)} entries\")\n", "print(\"\\nMapping preview:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "print(\"\\nApplying gene mapping to convert probe measurements to gene expression...\")\n", "\n", "# Use the library function to map probes to genes\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "print(f\"Converted data to {len(gene_data.index)} unique genes\")\n", "print(\"\\nFirst few gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Print shape of resulting gene expression matrix\n", "print(f\"\\nGene expression matrix shape: {gene_data.shape}\")\n" ] }, { "cell_type": "markdown", "id": "c35bcce0", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "ce2e939c", "metadata": {}, "outputs": [], "source": [ "# 1. Get gene mapping function from previous step\n", "def extract_gene_symbols(assignment):\n", " if isinstance(assignment, str) and assignment != '---':\n", " # Extract gene symbols that appear after '//' (typically the second element after splitting by '//')\n", " parts = assignment.split('//')\n", " if len(parts) >= 2:\n", " gene_symbol = parts[1].strip()\n", " return gene_symbol\n", " return None\n", "\n", "# 2. Get the file paths for the SOFT file and matrix file again\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 3. Retrieve and process gene data \n", "print(\"Retrieving gene expression data...\")\n", "gene_data_raw = get_genetic_data(matrix_file)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "gene_annotation['Gene'] = gene_annotation['gene_assignment'].apply(lambda x: extract_gene_symbols(x))\n", "mapping_df = gene_annotation[['ID', 'Gene']].copy().dropna()\n", "gene_data = apply_gene_mapping(gene_data_raw, mapping_df)\n", "print(f\"Retrieved gene expression data with shape: {gene_data.shape}\")\n", "\n", "# 4. Normalize gene symbols in the gene expression data\n", "print(\"Normalizing gene symbols in the expression data...\")\n", "try:\n", " # Normalize gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Save normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 5. Extract clinical data since it doesn't exist yet\n", "print(\"\\nExtracting clinical data...\")\n", "try:\n", " # Since we haven't yet extracted clinical features, do it now\n", " # First, read background information and clinical data from the matrix file\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Define conversion functions for trait (Down Syndrome), age, and gender\n", " def convert_trait(value):\n", " \"\"\"Convert trait value (Down Syndrome status) to binary (0 for control, 1 for DS)\"\"\"\n", " if value is None:\n", " return None\n", " # Extract the value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'DS':\n", " return 1\n", " elif value.upper() == 'CTL':\n", " return 0\n", " return None\n", "\n", " def convert_age(value):\n", " \"\"\"Convert age to a numeric value in years\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Extract numeric part and unit\n", " import re\n", " match = re.match(r'(\\d+)(\\w+)', value)\n", " if not match:\n", " return None\n", " \n", " number, unit = match.groups()\n", " number = float(number)\n", " \n", " # Convert to years based on unit\n", " if unit == 'yr':\n", " return number\n", " elif unit == 'mo':\n", " return number / 12\n", " elif unit == 'wg': # weeks of gestation\n", " return number / 52 # approximate conversion to years\n", " \n", " return None\n", "\n", " def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon and strip whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'F':\n", " return 0\n", " elif value.upper() == 'M':\n", " return 1\n", " \n", " return None\n", " \n", " # Based on earlier inspection, we know:\n", " # trait_row = 2 (disease status: CTL or DS)\n", " # age_row = 4 (age: with various values)\n", " # gender_row = 3 (Sex: F or M)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_data, \n", " trait=trait, \n", " trait_row=2, \n", " convert_trait=convert_trait,\n", " age_row=4, \n", " convert_age=convert_age, \n", " gender_row=3, \n", " convert_gender=convert_gender\n", " )\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data extracted and saved to {out_clinical_data_file}\")\n", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " \n", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " selected_clinical_df = pd.DataFrame() # Empty dataframe instead of None\n", " is_trait_available = False\n", "\n", "# 6. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if is_trait_available and is_gene_available:\n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # 7. Handle missing values systematically\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, data shape: {linked_data.shape}\")\n", " \n", " # 8. Determine whether features are biased\n", " print(\"\\nChecking for bias in features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " else:\n", " print(\"Cannot link data: gene or trait data is not available\")\n", " if is_trait_available:\n", " linked_data = selected_clinical_df.T # Use clinical data if available\n", " else:\n", " linked_data = pd.DataFrame({trait: [0, 1]}) # Minimal dataframe for validation\n", " is_biased = True\n", "except Exception as e:\n", " print(f\"Error in data linking or processing: {e}\")\n", " linked_data = pd.DataFrame({trait: [0, 1]}) # Minimal dataframe for validation\n", " is_biased = True\n", "\n", "# 9. Validate and save cohort info\n", "print(\"\\nPerforming final validation...\")\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=\"Down Syndrome dataset with gene expression from brain tissues across lifespan.\"\n", ")\n", "\n", "# 10. Save the linked data if usable\n", "if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Dataset not usable for {trait} association studies. Data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }