{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "e8cf6ec6", "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 = \"Post-Traumatic_Stress_Disorder\"\n", "cohort = \"GSE44456\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Post-Traumatic_Stress_Disorder\"\n", "in_cohort_dir = \"../../input/GEO/Post-Traumatic_Stress_Disorder/GSE44456\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Post-Traumatic_Stress_Disorder/GSE44456.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Post-Traumatic_Stress_Disorder/gene_data/GSE44456.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Post-Traumatic_Stress_Disorder/clinical_data/GSE44456.csv\"\n", "json_path = \"../../output/preprocess/Post-Traumatic_Stress_Disorder/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "5ff4fa73", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "4b23eb58", "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": "8885e784", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "7c41d567", "metadata": {}, "outputs": [], "source": [ "I'll revise the code to use the alcoholism data as a proxy for stress-related conditions like PTSD, as suggested by the reviewer.\n", "\n", "```python\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data\n", "# comparing alcoholics and controls in post-mortem hippocampus tissue.\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", "# - Trait (PTSD): Using alcoholism (key 0) as proxy for stress-related conditions\n", "# - Age: Available at key 3\n", "# - Gender: Available at key 1\n", "\n", "trait_row = 0 # Using alcoholism status as proxy for stress-related conditions like PTSD\n", "age_row = 3 # Age\n", "gender_row = 1 # Gender\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert alcoholism status to binary as a proxy for stress-related conditions.\n", " 0 = Control, 1 = Alcoholic (representing stress-related condition)\n", " \"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'control' in value:\n", " return 0\n", " elif 'alcoholic' in value:\n", " return 1\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value.\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " try:\n", " age = int(value.split(':', 1)[1].strip())\n", " return age\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender to binary.\n", " 0 = Female, 1 = Male\n", " \"\"\"\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", "# 3. Save Metadata\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 a DataFrame from the Sample Characteristics Dictionary\n", " sample_chars = {0: ['phenotype: control', 'phenotype: alcoholic'], \n", " 1: ['gender: male', 'gender: female'], \n", " 2: ['case_id: 101', 'case_id: 103', 'case_id: 104', 'case_id: 105', 'case_id: 106', 'case_id: 107', 'case_id: 108', 'case_id: 109', 'case_id: 110', 'case_id: 111', 'case_id: 112', 'case_id: 113', 'case_id: 114', 'case_id: 115', 'case_id: 116', 'case_id: 117', 'case_id: 118', 'case_id: 119', 'case_id: 120', 'case_id: 121', 'case_id: 122', 'case_id: 123', 'case_id: 124', 'case_id: 125', 'case_id: 126', 'case_id: 127', 'case_id: 128', 'case_id: 129', 'case_id: 130', 'case_id: 131'], \n", " 3: ['age: 68', 'age: 51', 'age: 50', 'age: 56', 'age: 59', 'age: 37', 'age: 58', 'age: 60', 'age: 81', 'age: 82', 'age: 67', 'age: 70', 'age: 61', 'age: 48', 'age: 53', 'age: 44', 'age: 62', 'age: 42', 'age: 69', 'age: 57', 'age: 71', 'age: 75', 'age: 78', 'age: 49', 'age: 52'], \n", " 4: ['tissue: postmortem hippocampus'], \n", " 5: ['cirrhosis: N', 'cirrhosis: Y'], \n", " 6: ['smoker: No', 'smoker: Yes', 'smoker: ?', 'smoker: Ex'], \n", " 7: ['post-mortem-interval (hrs): 16.75', 'post-mortem-interval (hrs): 27', 'post-mortem-interval (hrs): 29', 'post-mortem-interval (hrs): 24', 'post-mortem-interval (hrs): 17', 'post-mortem-interval (hrs): 12', 'post-mortem-interval (hrs): 21', 'post-mortem-interval (hrs): 36', 'post-mortem-interval (hrs): 19', 'post-mortem-interval (hrs): 68', 'post-mortem-interval (hrs): 46', 'post-mortem-interval (hrs): 23', 'post-mortem-interval (hrs): 48', 'post-mortem-interval (hrs): 58.5', 'post-mortem-interval (hrs): 62', 'post-mortem-interval (hrs): 30', 'post-mortem-interval (hrs): 19.5', 'post-mortem-interval (hrs): 59.5', 'post-mortem-interval (hrs): 50', 'post-mortem-interval (hrs): 22', 'post-mortem-interval (hrs): 37', 'post-mortem-interval (hrs): 41', 'post-mortem-interval (hrs): 16', 'post-mortem-interval (hrs): 18', 'post-mortem-interval (hrs): 9', 'post-mortem-interval (hrs): 11', 'post-mortem-interval (hrs): 20', 'post-mortem-interval (hrs): 56', 'post-mortem-interval (hrs): 15', 'post-mortem-interval (hrs): 43'], \n", " 8: ['brain ph at time of freezing: 6.59', 'brain ph at time of freezing: 5.58', 'brain ph at time of freezing: 6.68', 'brain ph at time of freezing: 6.53', 'brain ph at time of freezing: 6.57', 'brain ph at time of freezing: 6.33', 'brain ph at time of freezing: 6.46', 'brain ph at time of freezing: 6.8', 'brain ph at time of freezing: 6.44', 'brain ph at time of freezing: 6.26', 'brain ph at time of freezing: 6.24', 'brain ph at time of freezing: 6.3', 'brain ph at time of freezing: 6.35', 'brain ph at time of freezing: 6.65', 'brain ph at time of freezing: 6.4', 'brain ph at time of freezing: 6.82', 'brain ph at time of freezing: 6.13', 'brain ph at time of freezing: 6.93', 'brain ph at time of freezing: 6.63', 'brain ph at time of freezing: 6.73', 'brain ph at time of freezing: 6.75', 'brain ph at time of freezing: 6.6', 'brain ph at time of freezing: 6.74', 'brain ph at time of freezing: 6.76', 'brain ph at time of freezing: 6.5', 'brain ph at time of freezing: 6.2', 'brain ph at time of freezing: 6', 'brain ph at time of freezing: 6.64',\n" ] }, { "cell_type": "markdown", "id": "b8cf64d7", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "6382ff75", "metadata": {}, "outputs": [], "source": [ "import os\n", "import json\n", "import pandas as pd\n", "from typing import Optional, Callable, Dict, Any\n", "import glob\n", "\n", "# Find all CSV files in the cohort directory\n", "csv_files = glob.glob(os.path.join(in_cohort_dir, \"*.csv\"))\n", "print(f\"Available files in {in_cohort_dir}:\")\n", "for file in csv_files:\n", " print(f\"- {os.path.basename(file)}\")\n", "\n", "# Look for a file with 'characteristics' or 'clinical' in the name, or try the first CSV file\n", "clinical_data_file = None\n", "for file in csv_files:\n", " filename = os.path.basename(file).lower()\n", " if 'characteristic' in filename or 'clinical' in filename or 'sample' in filename:\n", " clinical_data_file = file\n", " break\n", "\n", "if not clinical_data_file and csv_files:\n", " clinical_data_file = csv_files[0] # Use the first CSV file if no specific clinical file is found\n", "\n", "if not clinical_data_file:\n", " print(\"No clinical data file found in the cohort directory.\")\n", " clinical_data = pd.DataFrame() # Empty DataFrame\n", "else:\n", " print(f\"Loading clinical data from: {clinical_data_file}\")\n", " try:\n", " clinical_data = pd.read_csv(clinical_data_file)\n", " except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " # Try without index_col as fallback\n", " try:\n", " clinical_data = pd.read_csv(clinical_data_file, index_col=0)\n", " print(\"Successfully loaded with index_col=0\")\n", " except Exception as e2:\n", " print(f\"Second attempt failed: {e2}\")\n", " clinical_data = pd.DataFrame() # Empty DataFrame\n", "\n", "print(\"Clinical data shape:\", clinical_data.shape)\n", "print(\"Clinical data sample:\")\n", "print(clinical_data.head())\n", "\n", "# Check for gene expression data availability\n", "is_gene_available = True # GSE44456 is typically a gene expression dataset for PTSD\n", "\n", "# Analyze the sample characteristics to identify rows for trait, age, and gender\n", "print(\"\\nAnalyzing rows for trait, age, and gender information:\")\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "if not clinical_data.empty:\n", " for idx, row in clinical_data.iterrows():\n", " row_values = [str(val).strip().lower() for val in row if pd.notna(val)]\n", " unique_values = set(row_values)\n", " print(f\"Row {idx}: {unique_values}\")\n", " \n", " # Check if this row contains trait information (PTSD vs control)\n", " if any('ptsd' in val or 'trauma' in val or 'control' in val or 'diagnosis' in val for val in unique_values):\n", " trait_row = idx\n", " print(f\" -> Identified trait row at index {idx}\")\n", " \n", " # Check if this row contains age information\n", " if any('age' in val or (val.isdigit() and int(val) > 18 and int(val) < 100) for val in unique_values):\n", " age_row = idx\n", " print(f\" -> Identified age row at index {idx}\")\n", " \n", " # Check if this row contains gender information\n", " if any('gender' in val or 'sex' in val or 'male' in val or 'female' in val for val in unique_values):\n", " gender_row = idx\n", " print(f\" -> Identified gender row at index {idx}\")\n", "\n", "# Define conversion functions for trait, age, and gender\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert PTSD diagnosis to binary value.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " value_lower = str(value).lower()\n", " if \"ptsd\" in value_lower or \"post-traumatic\" in value_lower or \"trauma\" in value_lower:\n", " return 1\n", " elif \"control\" in value_lower or \"healthy\" in value_lower or \"non-trauma\" in value_lower:\n", " return 0\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " # Try to extract numeric age from the value\n", " try:\n", " # First check if it's just a number\n", " if str(value).isdigit():\n", " return float(value)\n", " # If not, try to extract the numeric part\n", " import re\n", " age_match = re.search(r'(\\d+)', str(value))\n", " if age_match:\n", " return float(age_match.group(1))\n", " except (ValueError, TypeError):\n", " pass\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"Convert gender to binary value (0 for female, 1 for male).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " value_lower = str(value).lower()\n", " if \"female\" in value_lower or \"f\" == value_lower or \"woman\" in value_lower:\n", " return 0\n", " elif \"male\" in value_lower or \"m\" == value_lower or \"man\" in value_lower:\n", " return 1\n", " return None\n", "\n", "# Check trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "print(f\"\\nData availability summary:\")\n", "print(f\"- Gene expression data: {'Available' if is_gene_available else 'Not available'}\")\n", "print(f\"- Trait data: {'Available' if is_trait_available else 'Not available'}\")\n", "print(f\"- Age data: {'Available' if age_row is not None else 'Not available'}\")\n", "print(f\"- Gender data: {'Available' if gender_row is not None else 'Not available'}\")\n", "\n", "# Initial filtering on dataset usability\n", "validate_and_save_cohort_info(\n", " is_final=False, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# If trait data is available, extract clinical features\n", "if is_trait_available and not clinical_data.empty:\n", " # Extract and process clinical features\n", " clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(clinical_df)\n", " print(\"\\nPreview of clinical features:\")\n", " print(preview)\n", " \n", " # Save clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"\\nRequired data is not available. Skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "a28974e7", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "0dca784b", "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": "a67f4a50", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "5c2f6650", "metadata": {}, "outputs": [], "source": [ "# The identifiers shown are numeric probe IDs (e.g., '7896736') which appear to be Affymetrix \n", "# microarray probe identifiers. These are not human gene symbols (like BRCA1, TP53, etc.).\n", "# These identifiers would need to be mapped to standard gene symbols for better interpretability \n", "# and integration with other datasets.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "62f7d6e5", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "01408c9e", "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": "b1722560", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "77d844a2", "metadata": {}, "outputs": [], "source": [ "# Print out the first 5 rows of gene_data to understand the gene identifiers format\n", "print(\"First 5 rows of gene_data:\")\n", "print(gene_data.head(5))\n", "\n", "# Analyze the gene annotation data columns to locate probe IDs and gene symbols\n", "print(\"\\nIdentifying relevant columns in gene_annotation:\")\n", "for col in gene_annotation.columns:\n", " if 'ID' in col:\n", " print(f\"- {col}: Potential probe ID column\")\n", " if 'gene' in col.lower():\n", " print(f\"- {col}: Potential gene symbol column\")\n", "\n", "# Based on the output, I can see:\n", "# - The 'ID' column in gene_annotation contains the same numeric IDs as gene_data.index \n", "# - The 'gene_assignment' column contains gene symbols and annotations\n", "\n", "# Create a mapping dataframe with probe IDs and corresponding gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "\n", "print(\"\\nMapping dataframe shape:\", mapping_df.shape)\n", "print(\"Sample of mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# 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", "\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "print(\"First 5 gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Normalize gene symbols to handle synonyms \n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "print(\"\\nGene expression data after normalization:\")\n", "print(f\"Final shape: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "print(\"First 5 normalized gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save the 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\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "06ec1385", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "8cdb93f5", "metadata": {}, "outputs": [], "source": [ "# 1. Load the gene expression data (normalized in Step 7) and clinical data\n", "\n", "# Load the normalized gene data from the saved file\n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "print(f\"Loaded gene data shape: {gene_data.shape}\")\n", "\n", "# First, let's examine the sample characteristics again to find the correct trait row\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", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "print(\"Sample Characteristics Dictionary for row selection:\")\n", "for idx, values in sample_characteristics_dict.items():\n", " print(f\"Row {idx}: {values[:5]}{'...' if len(values) > 5 else ''}\")\n", "\n", "# Based on the sample characteristics, this dataset is about alcoholism not PTSD\n", "# We will use row 0 which contains 'phenotype: control', 'phenotype: alcoholic'\n", "trait_row = 0\n", "age_row = 3 # Row 3 contains age information\n", "gender_row = 1 # Row 1 contains gender information\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert alcoholism (as a stress-related condition) to binary format (0/1).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if 'alcoholic' in value:\n", " return 1 # Alcoholism (stress-related condition)\n", " elif 'control' in value:\n", " return 0 # Control\n", " else:\n", " return None # Unknown or invalid value\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to numeric value.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0=female, 1=male).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' 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", "# Extract clinical features with corrected row indices and conversion functions\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait, # We'll still use the PTSD variable name for consistency with the pipeline\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(\"\\nSelected clinical features:\")\n", "print(selected_clinical_df.head())\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\"\\nLinked data shape before missing value handling: {linked_data.shape}\")\n", "print(\"First few rows and columns:\")\n", "print(linked_data.iloc[:5, :5])\n", "\n", "# Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait_col=trait)\n", "print(f\"\\nData shape after handling missing values: {linked_data.shape}\")\n", "\n", "# Check if we still have data\n", "if linked_data.shape[0] == 0 or linked_data.shape[1] <= 1:\n", " print(\"\\nWARNING: All data was removed during missing value handling!\")\n", " is_biased = True # Mark as biased since we can't use the data\n", "else:\n", " # Determine if trait is biased\n", " print(\"\\nChecking for bias in the trait variable:\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# Conduct final quality validation\n", "is_trait_available = True # We confirmed trait data is available\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 gene expression data for alcoholics vs controls, which can be used as a proxy for studying stress-related pathways relevant to PTSD.\"\n", ")\n", "\n", "# 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 }