{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "789a2237", "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 = \"Hypothyroidism\"\n", "cohort = \"GSE75678\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Hypothyroidism\"\n", "in_cohort_dir = \"../../input/GEO/Hypothyroidism/GSE75678\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hypothyroidism/GSE75678.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hypothyroidism/gene_data/GSE75678.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hypothyroidism/clinical_data/GSE75678.csv\"\n", "json_path = \"../../output/preprocess/Hypothyroidism/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6883e690", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "a023020c", "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": "2a977840", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "d13bd76a", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset appears to contain gene expression data\n", "# from breast cancer tumors. It's not miRNA or methylation data.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For Hypothyroidism trait\n", "# Looking at the sample characteristics, we find personal pathological history at index 21,\n", "# which includes \"Hypothyroidism\" as one of the values\n", "trait_row = 21\n", "\n", "# For age\n", "# Age at diagnosis is available at index 19\n", "age_row = 19\n", "\n", "# For gender\n", "# Gender is available at index 1, but it shows only \"Female\" for all samples\n", "# Since it's constant (all Female), we'll set it to None as it's not useful for association studies\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "# Convert trait function - binary variable (0 = No hypothyroidism, 1 = Has hypothyroidism)\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if 'Hypothyroidism' in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "# Convert age function - continuous variable\n", "def convert_age(value):\n", " if pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "# Convert gender function - not needed as gender data is constant (all Female)\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata - 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", "# 4. Clinical Feature Extraction\n", "# If trait data is available, extract clinical features\n", "if trait_row is not None:\n", " # Create a more appropriate structure for the clinical data\n", " # First, identify all unique sample IDs\n", " sample_characteristics = {\n", " 0: ['tissue: Tumor Sample of Breast Cancer'], \n", " 1: ['gender: Female'], \n", " 2: ['rna ng/ul: 1083', 'rna ng/ul: 343', 'rna ng/ul: 111', 'rna ng/ul: 307', 'rna ng/ul: 401', 'rna ng/ul: 475', 'rna ng/ul: 728', 'rna ng/ul: 143.6', 'rna ng/ul: 224.7', 'rna ng/ul: 1458.3', 'rna ng/ul: 164', 'rna ng/ul: 370.2', 'rna ng/ul: 419.5', 'rna ng/ul: 693.6', 'rna ng/ul: 291.4', 'rna ng/ul: 1566.4', 'rna ng/ul: 69', 'rna ng/ul: 625.4', 'rna ng/ul: 151.6', 'rna ng/ul: 127.7', 'rna ng/ul: 1116.8', 'rna ng/ul: 333.9', 'rna ng/ul: 182.1', 'rna ng/ul: 437.4', 'rna ng/ul: 439', 'rna ng/ul: 178.2', 'rna ng/ul: 1365', 'rna ng/ul: 670', 'rna ng/ul: 840.6', 'rna ng/ul: 725'],\n", " 19: ['age at diagnosis: 45', 'age at diagnosis: 41', 'age at diagnosis: 59', 'age at diagnosis: 57', 'age at diagnosis: 42', 'age at diagnosis: 49', 'age at diagnosis: 54', 'age at diagnosis: 31', 'age at diagnosis: 70', 'age at diagnosis: 44', 'age at diagnosis: 50', 'age at diagnosis: 56', 'age at diagnosis: 51', 'age at diagnosis: 58', 'age at diagnosis: 55', 'age at diagnosis: 71', 'age at diagnosis: 40', 'age at diagnosis: 62', 'age at diagnosis: 87', 'age at diagnosis: 36', 'age at diagnosis: 43', 'age at diagnosis: 48', 'age at diagnosis: 66', 'age at diagnosis: 53', 'age at diagnosis: 35', 'age at diagnosis: 68', 'age at diagnosis: 46'],\n", " 21: ['personal pathological hystory: Neg', 'personal pathological hystory: Rheumatoid Arthritis', 'personal pathological hystory: Hypertension', 'personal pathological hystory: Apendicitis', 'personal pathological hystory: Hypertension and Diabetes', 'personal pathological hystory: Hypothyroidism', 'personal pathological hystory: Diabetes', 'personal pathological hystory: Ocular Surgery', 'personal pathological hystory: 3 C sections', 'personal pathological hystory: 0', 'personal pathological hystory: C section', 'personal pathological hystory: Hysterechtomy', 'personal pathological hystory: Dyslipidemia', 'personal pathological hystory: Hypertension and Rheumatoid Artritis', 'personal pathological hystory: Knee Surgery', 'personal pathological hystory: Venous insuficiency']\n", " }\n", " \n", " # Determine the maximum number of samples based on the traits we're interested in\n", " max_samples = max([len(sample_characteristics[row]) for row in [trait_row, age_row] if row is not None])\n", " \n", " # Create a DataFrame with one sample per row\n", " samples = []\n", " for i in range(max_samples):\n", " sample_data = {}\n", " \n", " # Add trait data if available for this sample\n", " if trait_row is not None and i < len(sample_characteristics[trait_row]):\n", " sample_data['characteristics'] = sample_characteristics[trait_row][i]\n", " sample_data['row'] = trait_row\n", " samples.append(sample_data.copy())\n", " \n", " # Add age data if available for this sample\n", " if age_row is not None and i < len(sample_characteristics[age_row]):\n", " sample_data['characteristics'] = sample_characteristics[age_row][i] \n", " sample_data['row'] = age_row\n", " samples.append(sample_data.copy())\n", " \n", " # Convert to DataFrame\n", " clinical_data = pd.DataFrame(samples)\n", " \n", " # Extract clinical features if there is data\n", " if not clinical_data.empty:\n", " # Use the geo_select_clinical_features function to extract features\n", " clinical_features = 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 features\n", " print(preview_df(clinical_features))\n", " \n", " # Save the clinical features to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " else:\n", " print(\"No clinical data available for processing.\")\n" ] }, { "cell_type": "markdown", "id": "013667be", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "258760a3", "metadata": {}, "outputs": [], "source": [ "# Load necessary libraries\n", "import os\n", "import json\n", "import pandas as pd\n", "import numpy as np\n", "import gzip\n", "from typing import Callable, Dict, Any, Optional\n", "\n", "# First, list files in the cohort directory to see what's available\n", "print(f\"Files in {in_cohort_dir}:\")\n", "files_in_dir = os.listdir(in_cohort_dir)\n", "print(files_in_dir)\n", "\n", "# Extract sample characteristics from series matrix file\n", "sample_characteristics = None\n", "series_matrix_file = None\n", "\n", "# Find the series matrix file\n", "for file in files_in_dir:\n", " if 'series_matrix.txt' in file:\n", " series_matrix_file = os.path.join(in_cohort_dir, file)\n", " break\n", "\n", "if series_matrix_file:\n", " print(f\"Found series matrix file: {series_matrix_file}\")\n", " try:\n", " # Open the gzipped file and extract relevant sections\n", " characteristics_lines = []\n", " with gzip.open(series_matrix_file, 'rt') as f:\n", " in_characteristics = False\n", " for line in f:\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " characteristics_lines.append(line.strip())\n", " elif line.startswith('!Sample_geo_accession'):\n", " # Get sample IDs\n", " sample_ids = line.strip().split('\\t')[1:]\n", " # Stop when we reach the data section\n", " elif line.startswith('!series_matrix_table_begin'):\n", " break\n", " \n", " if characteristics_lines:\n", " # Process the characteristics lines into a DataFrame\n", " data = []\n", " for i, line in enumerate(characteristics_lines):\n", " row_values = line.split('\\t')[1:] # Skip the first element (header)\n", " data.append(row_values)\n", " \n", " # Create a DataFrame with the characteristics data\n", " if data:\n", " sample_characteristics = pd.DataFrame(data)\n", " sample_characteristics.insert(0, '!Sample_geo_accession', [f\"Row_{i}\" for i in range(len(data))])\n", " \n", " # Display some information about the characteristics\n", " print(f\"Found {len(characteristics_lines)} characteristic rows\")\n", " \n", " # Get unique values for each row to analyze content\n", " unique_values = {}\n", " for i in range(len(sample_characteristics)):\n", " if i < sample_characteristics.shape[0]:\n", " values = [val.strip() if isinstance(val, str) else val for val in sample_characteristics.iloc[i, 1:]]\n", " unique_values[i] = list(set([val for val in values if pd.notna(val)]))\n", " \n", " print(f\"Unique values in sample characteristics:\")\n", " for key, values in unique_values.items():\n", " print(f\"Row {key}: {values}\")\n", " except Exception as e:\n", " print(f\"Error processing series matrix file: {e}\")\n", "else:\n", " print(\"Series matrix file not found\")\n", "\n", "# Check for gene expression data availability\n", "is_gene_available = series_matrix_file is not None\n", "print(f\"Gene expression data available: {is_gene_available}\")\n", "\n", "# Analyze unique values to determine trait, age, and gender rows\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Set these based on the analysis of unique values\n", "if sample_characteristics is not None:\n", " # Search for hypothyroidism-related information\n", " for i in range(len(sample_characteristics)):\n", " row_values = [str(val).lower() for val in sample_characteristics.iloc[i, 1:] if not pd.isna(val)]\n", " row_text = ' '.join(row_values)\n", " \n", " # Check for trait information\n", " if any(term in row_text for term in ['hypothyroid', 'thyroid', 'diagnosis', 'disease', 'condition', 'status', 'patient']):\n", " trait_row = i\n", " print(f\"Found trait information in row {i}: {unique_values[i]}\")\n", " \n", " # Check for age information\n", " elif any(term in row_text for term in ['age', 'year old']):\n", " age_row = i\n", " print(f\"Found age information in row {i}: {unique_values[i]}\")\n", " \n", " # Check for gender information\n", " elif any(term in row_text for term in ['gender', 'sex', 'male', 'female']):\n", " gender_row = i\n", " print(f\"Found gender information in row {i}: {unique_values[i]}\")\n", "\n", "# Define conversion functions\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert hypothyroidism status to binary format (1=patient, 0=control)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'hypothyroid' in value or 'patient' in value or 'case' in value or 'disease' in value:\n", " return 1\n", " elif 'control' in value or 'normal' in value or 'healthy' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"Convert age to continuous numerical value\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " # Check for common age patterns\n", " import re\n", " age_match = re.search(r'(\\d+(\\.\\d+)?)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " else:\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"Convert gender to binary format (0=female, 1=male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value in ['female', 'f', 'woman', 'women']:\n", " return 0\n", " elif value in ['male', 'm', 'man', 'men']:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "print(f\"Trait data available: {is_trait_available}\")\n", "\n", "# Conduct initial filtering and save metadata\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", "# Clinical Feature Extraction (if trait data and sample characteristics are available)\n", "if trait_row is not None and sample_characteristics is not None:\n", " # Extract clinical features using the helper function\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=sample_characteristics,\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_features)\n", " print(\"Preview of clinical features:\")\n", " print(preview)\n", " \n", " # Save clinical features to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"Clinical feature extraction skipped: trait data or sample characteristics not available\")\n" ] }, { "cell_type": "markdown", "id": "8281a8e6", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "a59599cc", "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": "878119fb", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "2e388d00", "metadata": {}, "outputs": [], "source": [ "# These identifiers appear to be just sequential numbers (1, 2, 3, etc.) which are not\n", "# human gene symbols. Human gene symbols typically look like BRCA1, TP53, etc.\n", "# These numeric IDs will need to be mapped to proper gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "1264b248", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "3142f899", "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": "faa835d9", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "568b1ecf", "metadata": {}, "outputs": [], "source": [ "# 1. Identify which columns in the gene annotation data correspond to gene IDs and gene symbols\n", "# From the preview, we can see the gene expression data uses numeric IDs (1, 2, 3, etc.)\n", "# The gene annotation data has an 'ID' column that appears to match these, and a 'GENE_SYMBOL' column for gene symbols\n", "\n", "# First, let's check how many rows have gene symbols\n", "num_rows_with_gene_symbols = gene_annotation['GENE_SYMBOL'].count()\n", "print(f\"Number of rows with gene symbols: {num_rows_with_gene_symbols} out of {len(gene_annotation)}\")\n", "\n", "# 2. Extract the mapping between gene IDs and gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'GENE_SYMBOL')\n", "print(f\"Generated gene mapping with {len(gene_mapping)} rows\")\n", "print(\"Preview of gene mapping:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply the gene mapping to convert from probe-level to gene-level expression\n", "print(\"\\nConverting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Generated gene expression data with {len(gene_data)} genes\")\n", "print(\"Preview of first few genes:\")\n", "print(gene_data.index[:20])\n", "\n", "# Save the gene expression data\n", "if not gene_data.empty:\n", " # Ensure the output directory exists\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", "else:\n", " print(\"Warning: Gene expression data is empty, no file saved\")\n" ] }, { "cell_type": "markdown", "id": "11a46ba2", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "f0f06b3f", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols and extract from step 3 and 6\n", "# Load the gene expression data (already loaded from Step 6)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "\n", "try:\n", " # Normalize gene symbols using the NCBI Gene database information\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " \n", " if normalized_gene_data.empty:\n", " print(\"Normalization resulted in empty dataframe. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " \n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data to the output file\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", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " # Save the original gene data if normalization fails\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", "\n", "# 2. Link clinical and genetic data\n", "# Use the trait_row identified in Step 2 (trait_row = 1) to extract trait data\n", "is_trait_available = trait_row is not None\n", "\n", "if is_trait_available:\n", " # Extract clinical features using the function and conversion methods from Step 2\n", " clinical_features = 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 features\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.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(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", "else:\n", " # Create a minimal dataframe with just the trait column\n", " linked_data = pd.DataFrame({trait: [np.nan]})\n", " print(\"No trait data available, creating minimal dataframe for validation.\")\n", "\n", "# 3. Handle missing values in the linked data\n", "if is_trait_available:\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After missing value handling, linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Determine whether trait and demographic features are biased\n", "if is_trait_available and not linked_data.empty and len(linked_data.columns) > 1:\n", " print(\"\\nEvaluating feature bias...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Trait bias evaluation result: {is_biased}\")\n", "else:\n", " is_biased = False\n", " print(\"Skipping bias evaluation due to insufficient data.\")\n", "\n", "# 5. Final validation and save metadata\n", "note = \"\"\n", "if not is_trait_available:\n", " note = f\"Dataset contains gene expression data but no {trait} measurements.\"\n", "elif is_biased:\n", " note = f\"Dataset contains {trait} data but its distribution is severely biased.\"\n", "\n", "# Validate and save cohort info\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=note\n", ")\n", "\n", "# 6. Save the linked data if usable\n", "print(f\"\\nDataset usability: {is_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(f\"Dataset is not usable for {trait} association studies. Data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }