{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "614727c4", "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 = \"Anxiety_disorder\"\n", "cohort = \"GSE61672\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Anxiety_disorder\"\n", "in_cohort_dir = \"../../input/GEO/Anxiety_disorder/GSE61672\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Anxiety_disorder/GSE61672.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Anxiety_disorder/gene_data/GSE61672.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Anxiety_disorder/clinical_data/GSE61672.csv\"\n", "json_path = \"../../output/preprocess/Anxiety_disorder/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "fd17ee20", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "efc0d9c8", "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": "88c3071e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "6f60ae20", "metadata": {}, "outputs": [], "source": [ "I need to analyze the data and implement proper clinical feature extraction for this GEO dataset. Let me write valid Python code to handle this task.\n", "\n", "```python\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this is gene expression data from blood samples\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary:\n", "# - Age data is in key 0\n", "# - Sex/Gender data is in key 1\n", "# - Anxiety case/control status is in key 4\n", "trait_row = 4 # anxiety case/control is in key 4\n", "age_row = 0 # age\n", "gender_row = 1 # sex\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 for control, 1 for case)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if value.lower() == \"case\":\n", " return 1\n", " elif value.lower() == \"control\":\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric value\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\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", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available by checking if trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering and save cohort info\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 DataFrame from sample characteristics dictionary\n", " sample_chars = {\n", " 0: ['age: 44', 'age: 59', 'age: 39', 'age: 64', 'age: 58', 'age: 45', 'age: 37', 'age: 40', 'age: 57', 'age: 52', 'age: 62', 'age: 55', 'age: 53', 'age: 47', 'age: 48', 'age: 49', 'age: 35', 'age: 46', 'age: 54', 'age: 67', 'age: 51', 'age: 34', 'age: 60', 'age: 41', 'age: 38', 'age: 73', 'age: 28', 'age: 56', 'age: 71', 'age: 50'],\n", " 1: ['Sex: F', 'Sex: M', 'body mass index: 25.1', 'body mass index: 31.1', 'body mass index: 29.4', 'body mass index: 27.6', 'body mass index: 24.6', 'body mass index: 28', 'body mass index: 33.9', 'body mass index: 35', 'body mass index: 18.1', 'body mass index: 19.2', 'body mass index: 39.2', 'body mass index: 26.8', 'body mass index: 21.3', 'body mass index: 36.5', 'body mass index: 19.5', 'body mass index: 24.4', 'body mass index: 26.4', 'body mass index: 26.2', 'body mass index: 23.8', 'body mass index: 19.7', 'body mass index: 30.6', 'body mass index: 22.8', 'body mass index: 22.1', 'body mass index: 33.4', 'body mass index: 26.6', 'body mass index: 21.8', 'body mass index: 24.3', 'body mass index: 27'],\n", " 2: ['body mass index: 22.2', 'body mass index: 33.1', 'body mass index: 22.4', 'body mass index: 20.6', 'body mass index: 27.5', 'body mass index: 21.9', 'body mass index: 26.1', 'body mass index: 34.8', 'body mass index: 20.8', 'body mass index: 23.3', 'body mass index: 22.7', 'body mass index: 26.4', 'body mass index: 32.5', 'body mass index: 21.6', 'body mass index: 27.6', 'body mass index: 25.7', 'body mass index: 33.3', 'body mass index: 31.6', 'body mass index: 28', 'body mass index: 41.1', 'body mass index: 19.7', 'body mass index: 22.1', 'body mass index: 20.7', 'body mass index: 30.9', 'body mass index: 17.8', 'body mass index: 22.5', 'body mass index: 40.6', 'body mass index: 28.9', 'body mass index: 26', 'body mass index: 22'],\n", " 3: ['ethnicity: CAU', 'ethnicity: AFR', 'ethnicity: ASN', 'ethnicity: AMI', 'ethnicity: CAH', 'gad7 score: 6', 'gad7 score: 1', 'gad7 score: 0', 'gad7 score: 2', 'gad7 score: 3', 'gad7 score: 5', 'gad7 score: 4', 'gad7 score: 9', 'gad7 score: 7', 'gad7 score: 8', 'hybridization batch: C', 'gad7 score: .', 'gad7 score: 16', 'gad7 score: 12', 'gad7 score: 11', 'gad7 score: 21', 'gad7 score: 18', 'gad7 score: 14'],\n", " 4: ['gad7 score: 2', 'gad7 score: 0', 'gad7 score: 3', 'gad7 score: 7', 'gad7 score: 4', 'gad7 score: 9', 'gad7 score: 1', 'gad7 score: 10', 'gad7 score: 5', 'gad7 score: 17', 'gad7 score: 6', 'gad7 score: 8', 'gad7 score: 12', 'gad7 score: 11', 'gad7 score: 14', 'gad7 score: .', 'hybridization batch: Z', 'gad7 score: 18', 'hybridization batch: O', 'gad7 score: 13', 'gad7 score: 15', 'gad7 score: 20', 'gad7 score: 21', 'gad7 score: 19', 'anxiety case/control: case', 'anxiety case/control: control', 'hybridization batch\n" ] }, { "cell_type": "markdown", "id": "d5a6fe94", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "dd14e294", "metadata": {}, "outputs": [], "source": [ "I understand I need to fix the code to properly analyze the GEO series matrix file and extract clinical data.\n", "\n", "```python\n", "# Let's analyze the dataset to extract clinical features\n", "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "import gzip\n", "import re\n", "from typing import Callable, Optional, Dict, Any, List, Union\n", "\n", "# Let's check files in the cohort directory\n", "files_in_cohort = os.listdir(in_cohort_dir)\n", "print(f\"Files in cohort directory: {files_in_cohort}\")\n", "\n", "# Initialize variables\n", "is_gene_available = False\n", "is_trait_available = False\n", "clinical_data = None\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Parse the GEO series matrix file which contains both gene expression and clinical data\n", "matrix_file = os.path.join(in_cohort_dir, \"GSE61672_series_matrix.txt.gz\")\n", "if os.path.exists(matrix_file):\n", " # Read the gzipped file line by line to extract sample characteristics\n", " characteristics_dict = {}\n", " sample_ids = []\n", " \n", " try:\n", " with gzip.open(matrix_file, 'rt') as f:\n", " in_header_section = True\n", " row_idx = 0\n", " \n", " for line in f:\n", " line = line.strip()\n", " \n", " # Check if we've reached the gene expression data\n", " if line.startswith(\"!series_matrix_table_begin\"):\n", " is_gene_available = True\n", " in_header_section = False\n", " continue\n", " \n", " if in_header_section and line.startswith(\"!Sample_\"):\n", " parts = line.split('\\t')\n", " header = parts[0]\n", " values = parts[1:]\n", " \n", " # Get sample IDs once\n", " if header == \"!Sample_geo_accession\":\n", " sample_ids = [v.strip('\"') for v in values]\n", " \n", " # Store characteristics\n", " if header == \"!Sample_characteristics_ch1\":\n", " # This might have multiple rows for different characteristics\n", " if \"!Sample_characteristics_ch1\" not in characteristics_dict:\n", " characteristics_dict[\"!Sample_characteristics_ch1\"] = []\n", " characteristics_dict[\"!Sample_characteristics_ch1\"].append(values)\n", " row_idx += 1\n", " else:\n", " characteristics_dict[header] = values\n", " \n", " # Process characteristics to find trait, age, and gender\n", " if \"!Sample_characteristics_ch1\" in characteristics_dict:\n", " # Create DataFrame from characteristics\n", " clinical_rows = []\n", " clinical_row_names = []\n", " \n", " # Process each characteristics row\n", " for i, chars_row in enumerate(characteristics_dict[\"!Sample_characteristics_ch1\"]):\n", " # Extract the characteristic name and create a dictionary for the row\n", " row_data = {}\n", " char_name = None\n", " \n", " # Get first value to extract characteristic name\n", " if chars_row and chars_row[0]:\n", " first_value = chars_row[0].strip('\"')\n", " if \":\" in first_value:\n", " char_name = first_value.split(':', 1)[0].strip()\n", " \n", " # Skip if no name could be extracted\n", " if not char_name:\n", " continue\n", " \n", " # Process all values in the row\n", " for j, value in enumerate(chars_row):\n", " value = value.strip('\"')\n", " # Skip empty values\n", " if not value:\n", " continue\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " row_data[sample_ids[j] if j < len(sample_ids) else f\"Sample_{j}\"] = value\n", " \n", " # Add row to data\n", " if row_data:\n", " clinical_rows.append(row_data)\n", " clinical_row_names.append(char_name)\n", " \n", " # Create DataFrame from the rows\n", " if clinical_rows:\n", " clinical_data = pd.DataFrame(clinical_rows, index=clinical_row_names)\n", " \n", " # Print sample characteristics to identify trait, age, and gender rows\n", " print(\"Clinical data rows:\")\n", " for i, row_name in enumerate(clinical_data.index):\n", " print(f\"Row {i}, Name: {row_name}\")\n", " unique_values = clinical_data.iloc[i].unique()\n", " print(f\"Unique values: {unique_values[:5]}{'...' if len(unique_values) > 5 else ''}\")\n", " print()\n", " \n", " # Look for trait information (anxiety disorder)\n", " for i, row_name in enumerate(clinical_data.index):\n", " row_name_lower = row_name.lower()\n", " if 'disease' in row_name_lower or 'diagnosis' in row_name_lower or 'condition' in row_name_lower or 'status' in row_name_lower or 'anxiety' in row_name_lower:\n", " unique_vals = clinical_data.iloc[i].unique()\n", " # Check if values suggest anxiety disorder vs control\n", " has_trait_info = any(('anxiety' in str(val).lower() or 'control' in str(val).lower() or \n", " 'patient' in str(val).lower() or 'healthy' in str(val).lower() or\n", " 'ptsd' in str(val).lower() or 'disorder' in str(val).lower()) \n", " for val in unique_vals)\n", " if has_trait_info and len(unique_vals) > 1: # Ensure there's more than one value\n", " trait_row = i\n", " break\n", " \n", " # Look for age information\n", " for i, row_name in enumerate(clinical_data.index):\n", " row_name_lower = row_name.lower()\n", " if 'age' in row_name_lower:\n", " unique_vals = clinical_data.iloc[i].unique()\n", " if len(unique_vals) > 1: # Ensure there's more than one value\n", " age_row = i\n", " break\n", " \n", " # Look for gender information\n", " for i, row_name in enumerate(clinical_data.index):\n", " row_name_lower = row_name.lower()\n", " if 'gender' in row_name_lower or 'sex' in row_name_lower:\n", " unique_vals = clinical_data.iloc[i].unique()\n", " if len(unique_vals) > 1: # Ensure there's more than one value\n", " gender_row = i\n", " break\n", " \n", " print(f\"Identified trait_row: {trait_row}\")\n", " print(f\"Identified age_row: {age_row}\")\n", " print(f\"Identified gender_row: {gender_row}\")\n", " \n", " except Exception as e:\n", " print(f\"Error reading matrix file: {e}\")\n", " import traceback\n", " traceback.print_exc()\n", "else:\n", " print(\"Series matrix file not found.\")\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary (0 for control, 1 for case)\"\"\"\n", " if pd.isna(value) or value is None or value == '':\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " # Map to binary values\n", " if 'control' in value or 'healthy' in value or 'normal' in value:\n", " return 0\n", " elif 'patient' in value or 'anxiety' in value or 'disorder' in value or 'case' in value or 'ptsd' in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to numeric\"\"\"\n", " if pd.isna(value) or value is None or value == '':\n", " return None\n", " \n", " # Try to extract numeric value\n", " try:\n", " # Extract just digits and decimal points\n", " numbers = re.findall(r'\\d+\\.?\\d*', str(value))\n", " if numbers:\n", " return float(numbers[0])\n", " else:\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_\n" ] }, { "cell_type": "markdown", "id": "68c8e933", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "b08ac106", "metadata": {}, "outputs": [], "source": [ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract the gene expression 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)\n", "print(\"\\nFirst 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n", "\n", "# 4. Print the dimensions of the gene expression data\n", "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "\n", "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "c1daf6d4", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "262754cb", "metadata": {}, "outputs": [], "source": [ "# These identifiers are Illumina probe IDs (ILMN_xxxxxxx format)\n", "# They are not human gene symbols and will require mapping to proper gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "be897ed6", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "d6a7209e", "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": "65062464", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "6acf48b1", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the columns for probe IDs and gene symbols in gene_annotation\n", "# From the preview, we see:\n", "# - 'ID' contains the probe identifiers (e.g., ILMN_1343048) which match our gene expression data\n", "# - 'Symbol' contains the gene symbols (e.g., phage_lambda_genome, thrB)\n", "\n", "# 2. Create a mapping dataframe with probe IDs and gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col=\"ID\", gene_col=\"Symbol\")\n", "print(f\"Shape of gene mapping dataframe: {gene_mapping.shape}\")\n", "print(f\"First 5 rows of gene mapping:\")\n", "print(gene_mapping.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, gene_mapping)\n", "print(f\"\\nShape of gene-level expression data: {gene_data.shape}\")\n", "print(f\"First 5 gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Normalize gene symbols to ensure consistency\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"\\nShape after normalization: {gene_data.shape}\")\n", "print(f\"First 5 normalized gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save the gene 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": "5597e018", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "9cd5cf7a", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data (already normalized in step 7)\n", "print(\"Gene data already normalized in previous step\")\n", "\n", "# 2. Extract clinical data\n", "# First, get the paths again\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Get background information and 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", "# Print unique values by row to verify indices\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(\"Unique values by row (first 5 for each):\")\n", "for row_idx, values in sample_characteristics_dict.items():\n", " print(f\"Row {row_idx}: {values[:5]}\")\n", "\n", "# Based on the sample characteristics dictionary\n", "# Row 5 contains the anxiety case/control status\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " if \":\" not in str(value):\n", " return None\n", " \n", " value = str(value).split(\":\", 1)[1].strip().lower()\n", " if \"case\" in value:\n", " return 1\n", " elif \"control\" in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value):\n", " return None\n", " if \":\" not in str(value):\n", " return None\n", " \n", " value = str(value).split(\":\", 1)[1].strip()\n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value):\n", " return None\n", " if \":\" not in str(value):\n", " return None\n", " \n", " value = str(value).split(\":\", 1)[1].strip().lower()\n", " if value == \"f\":\n", " return 0\n", " elif value == \"m\":\n", " return 1\n", " return None\n", "\n", "# Use the correct row indices based on the sample characteristics dict output\n", "trait_row = 5 # anxiety case/control in row 5\n", "age_row = 0 # age in row 0\n", "gender_row = 1 # Sex: F/M in row 1\n", "\n", "# Extract clinical features\n", "print(\"Extracting clinical features...\")\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", ")\n", "\n", "print(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_df))\n", "print(f\"Clinical data contains trait values: {selected_clinical_df.loc[trait].notna().any()}\")\n", "\n", "# Save clinical data if it has trait values\n", "if selected_clinical_df.loc[trait].notna().any():\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", " # 3. Link clinical and genetic data using previously normalized gene data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n", " print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", "\n", " # 4. Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait_col=trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", " # 5. Determine if trait and demographic features are biased\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", " # 6. Conduct final quality 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=True,\n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains human anxiety disorder data with gene expression, age, and gender information.\"\n", " )\n", "\n", " # 7. Save linked data if usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")\n", "else:\n", " print(\"No valid trait data found. Dataset cannot be used for trait association studies.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid anxiety disorder trait data found in this dataset.\"\n", " )\n" ] }, { "cell_type": "markdown", "id": "5864b9ff", "metadata": {}, "source": [ "### Step 9: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "50a1c0ef", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"Normalizing gene symbols...\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "print(f\"First 5 normalized gene symbols: {normalized_gene_data.index[:5].tolist()}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Re-extract clinical data since step 2 identified that trait data is available\n", "# First, get the paths again\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Get background information and 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", "# Extract clinical features using the conversion functions defined in step 2\n", "def convert_trait(value):\n", " if not value or \":\" not in value:\n", " return None\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " if \"obsessive-compulsive disorder\" in value or \"ocd\" in value:\n", " # OCD is considered an anxiety-related disorder in this study\n", " return 1\n", " elif \"normal control\" in value or \"control\" in value or \"healthy\" in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " if not value or \":\" not in value:\n", " return None\n", " value = value.split(\":\", 1)[1].strip()\n", " import re\n", " match = re.search(r'(\\d+)', value)\n", " if match:\n", " return int(match.group(1))\n", " return None\n", "\n", "def convert_gender(value):\n", " if not value or \":\" not in value:\n", " return None\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " return None\n", "\n", "# Using values identified in step 2\n", "trait_row = 1 # OCD status\n", "age_row = 3 # Age\n", "gender_row = 2 # Gender\n", "\n", "# Extract clinical features\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", ")\n", "\n", "# 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", "# 3. 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", "# 4. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait_col=trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine if trait and demographic features are biased\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. Conduct final quality validation\n", "is_trait_available = True # We confirmed trait data is available in step 2\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=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains human OCD data, which is relevant to anxiety disorders. Contains gene expression, age, and gender information.\"\n", ")\n", "\n", "# 7. Save linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }