{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a25f3d78", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:48.335731Z", "iopub.status.busy": "2025-03-25T05:41:48.335306Z", "iopub.status.idle": "2025-03-25T05:41:48.504311Z", "shell.execute_reply": "2025-03-25T05:41:48.503877Z" } }, "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 = \"Hepatitis\"\n", "cohort = \"GSE114783\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Hepatitis\"\n", "in_cohort_dir = \"../../input/GEO/Hepatitis/GSE114783\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hepatitis/GSE114783.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hepatitis/gene_data/GSE114783.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hepatitis/clinical_data/GSE114783.csv\"\n", "json_path = \"../../output/preprocess/Hepatitis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "24fa5f58", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "cda8cfea", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:48.505587Z", "iopub.status.busy": "2025-03-25T05:41:48.505435Z", "iopub.status.idle": "2025-03-25T05:41:48.611951Z", "shell.execute_reply": "2025-03-25T05:41:48.611608Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Microarray gene expression from hepatitis B virus infection to hepatocellular carcinoma\"\n", "!Series_summary\t\"Background: The pathogenesis of hepatitis B virus (HBV)-caused hepatocellular carcinoma (HCC) is complex and not fully understood. In clinical, the effective prevention and treatment of HCC rely on the accurate diagnosis. We developed a biology network approach to investigate the potential mechanisms and biomarkers of each stages from HBV infection to HCC. Methods Global gene profiling of healthy individuals (HC), HBV carriers (HBVC), chronic hepatitis B patients (CHB), liver cirrhosis (LC) and HCC was analyzed by gene array. Differentially expressed genes (DEG) were found by RVM (Random variance model) corrective ANOVA and STC (Series Test of Cluster) analysis.\"\n", "!Series_overall_design\t\"peripheral blood mononuclear cells (PBMCs) from 3 healthy individuals (HC),3 HBV carriers (HBVC), 3 chronic hepatitis B patients (CHB), 3 liver cirrhosis (LC) and 3hepatocellular carcinoma (HCC) samples\"\n", "Sample Characteristics Dictionary:\n", "{0: ['diagnosis: hepatocellular carcinoma', 'diagnosis: liver cirrhosis', 'diagnosis: healthy control', 'diagnosis: chronic hepatitis B', 'diagnosis: hepatitis B virus carrier'], 1: ['cell type: PBMC']}\n" ] } ], "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": "da42b164", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "958918a2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:48.613226Z", "iopub.status.busy": "2025-03-25T05:41:48.613101Z", "iopub.status.idle": "2025-03-25T05:41:48.618053Z", "shell.execute_reply": "2025-03-25T05:41:48.617721Z" } }, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Callable, Dict, Any, Optional\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains microarray gene expression data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait (Hepatitis status)\n", "trait_row = 0 # The key 0 contains 'diagnosis' which indicates different hepatitis stages\n", "\n", "# Age and gender are not explicitly given in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert hepatitis status to binary values (0 for non-hepatitis, 1 for hepatitis-related conditions)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " value = value.lower()\n", " \n", " # Healthy control is non-hepatitis\n", " if 'healthy control' in value:\n", " return 0\n", " # All other values indicate hepatitis-related conditions\n", " elif any(condition in value for condition in ['hepatocellular carcinoma', 'liver cirrhosis', \n", " 'chronic hepatitis b', 'hepatitis b virus carrier']):\n", " return 1\n", " else:\n", " return None\n", "\n", "# Define conversion functions for age and gender (not used but needed for function calls)\n", "def convert_age(value):\n", " \"\"\"Convert age to float (not used in this dataset)\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (not used in this dataset)\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Initial filtering on usability\n", "is_trait_available = trait_row is not None\n", "is_initial_filtering_passed = 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", " # Load the clinical data\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_csv(clinical_data_path)\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", " # Preview the data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the 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, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "a440aacc", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "b97a6701", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:48.619109Z", "iopub.status.busy": "2025-03-25T05:41:48.618986Z", "iopub.status.idle": "2025-03-25T05:41:48.753148Z", "shell.execute_reply": "2025-03-25T05:41:48.752598Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n", "Successfully extracted gene data with 30141 rows\n", "First 20 gene IDs:\n", "Index(['AB000409', 'AB000463', 'AB000781', 'AB002294', 'AB002308', 'AB002313',\n", " 'AB002381', 'AB002382', 'AB003177', 'AB003333', 'AB007457', 'AB007870',\n", " 'AB007895', 'AB007921', 'AB007923', 'AB007928', 'AB007937', 'AB007940',\n", " 'AB010419', 'AB010962'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\n" ] } ], "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": "7124b4f7", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "bacf7865", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:48.754570Z", "iopub.status.busy": "2025-03-25T05:41:48.754448Z", "iopub.status.idle": "2025-03-25T05:41:48.756564Z", "shell.execute_reply": "2025-03-25T05:41:48.756188Z" } }, "outputs": [], "source": [ "# The gene identifiers in the data are accession numbers (like AB000409), not standard human gene symbols\n", "# These are identifiers for sequences in GenBank/EMBL/DDBJ databases\n", "# They need to be mapped to standard human gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "5661339c", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "61843c9b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:48.757983Z", "iopub.status.busy": "2025-03-25T05:41:48.757871Z", "iopub.status.idle": "2025-03-25T05:41:49.939440Z", "shell.execute_reply": "2025-03-25T05:41:49.938812Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 1130145 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['AB000409', 'AB000463', 'AB000781', 'AB001328', 'AB002294'], 'GB_ACC': ['AB000409', 'AB000463', 'AB000781', 'AB001328', 'AB002294'], 'GENE_ID': [8569.0, 6452.0, 85442.0, 6564.0, 9726.0]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'GB_ACC', 'GENE_ID']\n", "\n", "The GENE_ID column contains Entrez Gene IDs, not human gene symbols.\n", "\n", "Searching for more detailed gene annotation in the SOFT file...\n", "Platform ID: GPL15491\n", "\n", "We need to map from Entrez Gene IDs to gene symbols.\n", "Checking if the gene_synonym.json file contains the mapping information...\n", "Gene synonym file not found. We'll need another method to map IDs to symbols.\n", "\n", "Saving gene annotation for mapping step...\n", "Mapping data preview:\n", "{'ID': ['AB000409', 'AB000463', 'AB000781', 'AB001328', 'AB002294'], 'Gene': ['8569', '6452', '85442', '6564', '9726']}\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # First attempt - 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", " # The GENE_ID column contains Entrez Gene IDs, not gene symbols\n", " print(\"\\nThe GENE_ID column contains Entrez Gene IDs, not human gene symbols.\")\n", " \n", " # Try to find additional annotation information in the SOFT file\n", " print(\"\\nSearching for more detailed gene annotation in the SOFT file...\")\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Look for platform ID\n", " platform_id = None\n", " for line in file:\n", " if line.startswith('!Series_platform_id'):\n", " platform_id = line.split('=')[1].strip()\n", " print(f\"Platform ID: {platform_id}\")\n", " break\n", " \n", " # Since we need to map Entrez Gene IDs to gene symbols, we'll need to use an external mapping\n", " print(\"\\nWe need to map from Entrez Gene IDs to gene symbols.\")\n", " print(\"Checking if the gene_synonym.json file contains the mapping information...\")\n", " \n", " # Check if the gene synonym file exists and load it to see its structure\n", " synonym_path = \"./metadata/gene_synonym.json\"\n", " if os.path.exists(synonym_path):\n", " with open(synonym_path, \"r\") as f:\n", " synonym_dict = json.load(f)\n", " print(f\"Found gene synonym dictionary with {len(synonym_dict)} entries.\")\n", " # Show a few sample entries if available\n", " sample_keys = list(synonym_dict.keys())[:5]\n", " print(f\"Sample entries: {sample_keys}\")\n", " else:\n", " print(\"Gene synonym file not found. We'll need another method to map IDs to symbols.\")\n", " \n", " # Save the gene annotation for later use in mapping\n", " print(\"\\nSaving gene annotation for mapping step...\")\n", " mapping_data = gene_annotation[['ID', 'GENE_ID']].dropna()\n", " mapping_data = mapping_data.rename(columns={'GENE_ID': 'Gene'})\n", " mapping_data['Gene'] = mapping_data['Gene'].astype(int).astype(str)\n", " \n", " # Show a preview of the mapping data\n", " print(\"Mapping data preview:\")\n", " print(preview_df(mapping_data))\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "e4f12f43", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "76915c71", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:49.941386Z", "iopub.status.busy": "2025-03-25T05:41:49.941237Z", "iopub.status.idle": "2025-03-25T05:41:50.116663Z", "shell.execute_reply": "2025-03-25T05:41:50.116134Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping dataframe...\n", "Created mapping dataframe with 42947 rows\n", "Mapping preview:\n", "{'ID': ['AB000409', 'AB000463', 'AB000781', 'AB001328', 'AB002294'], 'Gene': ['8569', '6452', '85442', '6564', '9726']}\n", "\n", "Applying gene mapping to convert probe-level measurements to gene expression data...\n", "Converted gene expression data: 5272 genes × 36 samples\n", "\n", "Normalizing gene symbols to standard format...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 0 genes × 36 samples\n", "First 10 normalized gene symbols:\n", "[]\n", "Processed gene data saved to ../../output/preprocess/Hepatitis/gene_data/GSE114783.csv\n", "\n", "Gene data processing completed.\n" ] } ], "source": [ "# 1. Decide which columns to use for mapping\n", "gene_id_column = 'ID' # The probe ID in gene annotation data \n", "gene_symbol_column = 'GENE_ID' # The Entrez Gene ID in gene annotation data\n", "\n", "# 2. Get the gene mapping dataframe\n", "print(\"Creating gene mapping dataframe...\")\n", "mapping_df = gene_annotation[['ID', 'GENE_ID']].dropna()\n", "mapping_df = mapping_df.rename(columns={'GENE_ID': 'Gene'})\n", "\n", "# Convert Entrez IDs to strings in a format that works with the mapping functions\n", "mapping_df['Gene'] = mapping_df['Gene'].astype(float).astype(int).astype(str)\n", "print(f\"Created mapping dataframe with {len(mapping_df)} rows\")\n", "print(\"Mapping preview:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "print(\"\\nApplying gene mapping to convert probe-level measurements to gene expression data...\")\n", "try:\n", " # Instead of using the extract_human_gene_symbols function which is designed for text,\n", " # we'll modify our mapping data to work with the existing pipeline\n", " # Wrap each Entrez ID in a format that mimics gene symbols for the extraction function\n", " def format_entrez_id(entrez_id):\n", " # Create a temporary tag that will pass through extract_human_gene_symbols\n", " return f\"ENTREZ{entrez_id}\"\n", " \n", " # Apply this formatting to create 'Gene' values that will work with the extraction\n", " mapping_df['Gene'] = mapping_df['Gene'].apply(format_entrez_id)\n", " \n", " # Now apply the gene mapping\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " print(f\"Converted gene expression data: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", " \n", " # 4. Normalize gene symbols if we have gene data\n", " if gene_data.shape[0] > 0:\n", " print(\"\\nNormalizing gene symbols to standard format...\")\n", " \n", " # Apply a function to convert our temporary format back before normalization\n", " gene_data.index = gene_data.index.str.replace('ENTREZ', '')\n", " \n", " # Now normalize using the standard function which will map Entrez IDs to symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {normalized_gene_data.shape[0]} genes × {normalized_gene_data.shape[1]} samples\")\n", " \n", " # Preview the first few gene symbols after normalization\n", " print(\"First 10 normalized gene symbols:\")\n", " print(normalized_gene_data.index[:10].tolist())\n", " \n", " # Save the processed 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\"Processed gene data saved to {out_gene_data_file}\")\n", " \n", " # Set the final gene data for further processing\n", " gene_data = normalized_gene_data\n", " else:\n", " print(\"WARNING: No genes were mapped successfully. Gene data is empty.\")\n", " \n", " # Alternative approach - try using direct mapping instead\n", " print(\"\\nAttempting direct mapping using original gene annotation...\")\n", " # Use entrez IDs directly as gene IDs for the normalize_gene_symbols_in_index step\n", " gene_data = gene_annotation.set_index('GENE_ID').join(\n", " gene_data.T, on='ID', how='inner'\n", " ).T\n", " \n", " if gene_data.shape[0] > 0:\n", " # Convert index to strings\n", " gene_data.index = gene_data.index.astype(str)\n", " \n", " # Normalize using the standard function\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After direct mapping: {normalized_gene_data.shape[0]} genes × {normalized_gene_data.shape[1]} samples\")\n", " \n", " # Save the processed 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\"Processed gene data saved to {out_gene_data_file}\")\n", " \n", " # Set the final gene data for further processing\n", " gene_data = normalized_gene_data\n", " else:\n", " print(\"WARNING: Alternative mapping also failed. Gene data remains empty.\")\n", " \n", "except Exception as e:\n", " print(f\"Error in gene mapping process: {e}\")\n", " import traceback\n", " traceback.print_exc()\n", " print(\"Unable to complete gene mapping.\")\n", "\n", "print(\"\\nGene data processing completed.\")\n" ] }, { "cell_type": "markdown", "id": "c92455d6", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "6fe65d93", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:50.118479Z", "iopub.status.busy": "2025-03-25T05:41:50.118335Z", "iopub.status.idle": "2025-03-25T05:41:50.206310Z", "shell.execute_reply": "2025-03-25T05:41:50.205668Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (0, 36)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalization resulted in empty dataframe. Using original gene data instead.\n", "Gene data shape after normalization: (0, 36)\n", "Normalized gene data saved to ../../output/preprocess/Hepatitis/gene_data/GSE114783.csv\n", "Clinical data saved to ../../output/preprocess/Hepatitis/clinical_data/GSE114783.csv\n", "Linked data shape: (36, 1)\n", "\n", "Handling missing values...\n", "After missing value handling, linked data shape: (0, 1)\n", "Skipping bias evaluation due to insufficient data.\n", "Abnormality detected in the cohort: GSE114783. Preprocessing failed.\n", "A new JSON file was created at: ../../output/preprocess/Hepatitis/cohort_info.json\n", "\n", "Dataset usability: False\n", "Dataset is not usable for Hepatitis association studies. Data not saved.\n" ] } ], "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": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }