{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "6adcebbc", "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 = \"Breast_Cancer\"\n", "cohort = \"GSE208101\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE208101\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Breast_Cancer/GSE208101.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE208101.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE208101.csv\"\n", "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "b5dc8926", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "fe978721", "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": "9877fcf7", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "2528582e", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the Series title and description, this dataset contains gene expression data using Clariom D platform\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Trait (Breast Cancer): Looking at the sample characteristics, we can see the disease state and loco-regional recurrence timing\n", "trait_row = 2 # loco-regional recurrence is our trait of interest (early, intermediate, late)\n", "age_row = None # Age information is not available in the sample characteristics\n", "gender_row = 0 # Gender information is available\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert loco-regional recurrence timing to binary values.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary: early (< 2 yrs) = 1, others = 0\n", " if \"EARLY\" in value.upper():\n", " return 1\n", " elif \"INTERMEDIATE\" in value.upper() or \"LATE\" in value.upper():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary values.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary: female = 0, male = 1\n", " if value.lower() == \"female\":\n", " return 0\n", " elif value.lower() == \"male\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# Since age_row is None, we don't need to define convert_age\n", "\n", "# 3. Save Metadata\n", "# Trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct 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", "# Since trait_row is not None, we proceed with clinical feature extraction\n", "try:\n", " # Load clinical data if available\n", " if os.path.exists(f\"{in_cohort_dir}/clinical_data.csv\"):\n", " clinical_data = pd.read_csv(f\"{in_cohort_dir}/clinical_data.csv\", index_col=0)\n", " \n", " # Extract clinical features using the imported function\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", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the processed clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical Data Preview:\")\n", " print(preview)\n", " \n", " # Save the processed 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\"Saved clinical data to {out_clinical_data_file}\")\n", " else:\n", " print(f\"Clinical data file not found at {in_cohort_dir}/clinical_data.csv\")\n", "except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "7c9d059a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "8ff1c980", "metadata": {}, "outputs": [], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "marker_row = None\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " marker_row = i\n", " print(f\"Found the matrix table marker at line {i}\")\n", " break\n", " \n", " if not found_marker:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " is_gene_available = False\n", " \n", " # If marker was found, try to extract gene data\n", " if is_gene_available:\n", " try:\n", " # Try using the library function\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " except Exception as e:\n", " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n", " is_gene_available = False\n", " \n", " # If gene data extraction failed, examine file content to diagnose\n", " if not is_gene_available:\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Print lines around the marker if found\n", " if marker_row is not None:\n", " for i, line in enumerate(file):\n", " if i >= marker_row - 2 and i <= marker_row + 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " if i > marker_row + 10:\n", " break\n", " else:\n", " # If marker not found, print first 10 lines\n", " for i, line in enumerate(file):\n", " if i < 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing file: {e}\")\n", " is_gene_available = False\n", "\n", "# Update validation information if gene data extraction failed\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n", " # Update the validation record since gene data isn't available\n", " is_trait_available = False # We already determined trait data isn't available in step 2\n", " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n" ] }, { "cell_type": "markdown", "id": "cdd548e4", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "e40127f5", "metadata": {}, "outputs": [], "source": [ "# These are not standard human gene symbols but rather appear to be probe identifiers from a microarray\n", "# or similar platform. They have a specific format (TC0100006432.hg.1) that suggests they need to be\n", "# mapped to actual human gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "755144f1", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "6a5c1323", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=3))\n", "\n", "# Looking at the output, the gene_assignment column contains gene symbols\n", "print(\"\\nExamining ID and gene_assignment columns format (first 3 rows):\")\n", "if 'ID' in gene_annotation.columns and 'gene_assignment' in gene_annotation.columns:\n", " for i in range(min(3, len(gene_annotation))):\n", " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, gene_assignment={gene_annotation['gene_assignment'].iloc[i]}\")\n", "\n", " # Check the quality and completeness of the mapping\n", " non_null_symbols = gene_annotation['gene_assignment'].notna().sum()\n", " total_rows = len(gene_annotation)\n", " print(f\"\\ngene_assignment column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n" ] }, { "cell_type": "markdown", "id": "27ecdc35", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "3847e24a", "metadata": {}, "outputs": [], "source": [ "# Extract the probe identifier (ID) and gene symbol (gene_assignment) columns\n", "# Looking at the output, we can see:\n", "# 1. The ID column in gene_annotation matches the probe IDs in gene_data\n", "# 2. The gene_assignment column contains gene symbol information but in a complex format\n", "\n", "# 1. First, get the gene expression data\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 2. Extract the mapping between probe IDs and gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "\n", "# 3. Convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Check the shape of the resulting gene expression dataframe\n", "print(f\"Converted gene expression data shape: {gene_data.shape}\")\n", "\n", "# Display a few gene symbols (indexes) in the gene expression data\n", "print(\"First 10 gene symbols in converted gene expression data:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Check for any issues with the data\n", "print(f\"Number of gene symbols after mapping: {len(gene_data.index)}\")\n", "print(f\"Number of samples: {gene_data.shape[1]}\")\n" ] }, { "cell_type": "markdown", "id": "f684299d", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "acd4fe52", "metadata": {}, "outputs": [], "source": [ "```python\n", "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to 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", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data - respecting the analysis from Step 2\n", "# From Step 2, we determined:\n", "trait_row = 2 # loco-regional recurrence\n", "age_row = None # Age information is not available\n", "gender_row = 0 # Gender information is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Define converter functions as done in Step 2\n", "def convert_trait(value):\n", " \"\"\"Convert loco-regional recurrence timing to binary values.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary: early (< 2 yrs) = 1, others = 0\n", " if \"EARLY\" in value.upper():\n", " return 1\n", " elif \"INTERMEDIATE\" in value.upper() or \"LATE\" in value.upper():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary values.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary: female = 0, male = 1\n", " if value.lower() == \"female\":\n", " return 0\n", " elif value.lower() == \"male\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# Skip clinical feature extraction when trait_row is None\n", "if is_trait_available:\n", " try:\n", " # Load the clinical data from file\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Extract clinical features - note we don't include age_row and convert_age since age_row is None\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", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted clinical data\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", " except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "else:\n", " print(f\"No trait data ({trait}) available in this dataset based on previous analysis.\")\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Debug the column names to ensure they match\n", " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n", " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n", " \n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression from luminal breast cancer patients with different loco-regional recurrence timing (early, intermediate, late).\"\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", " # Save the linked data if it's 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(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " 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=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # Create an empty DataFrame for metadata purposes\n", " empty_df = pd.DataFrame()\n", " \n", " # We can't procee\n" ] }, { "cell_type": "markdown", "id": "f7f25be6", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "505a6c10", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to 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", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data - respecting the analysis from Step 2\n", "# From Step 2, we determined:\n", "# trait_row = None # No Breast Cancer subtype data available\n", "# age_row = 2\n", "# gender_row = None\n", "is_trait_available = trait_row is not None\n", "\n", "# Skip clinical feature extraction when trait_row is None\n", "if is_trait_available:\n", " try:\n", " # Load the clinical data from file\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Extract clinical 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", " gender_row=gender_row,\n", " convert_gender=convert_gender,\n", " age_row=age_row,\n", " convert_age=convert_age\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted clinical data\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", " except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "else:\n", " print(f\"No trait data ({trait}) available in this dataset based on previous analysis.\")\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Debug the column names to ensure they match\n", " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n", " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n", " \n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\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", " # Save the linked data if it's 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(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " 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=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # Create an empty DataFrame for metadata purposes\n", " empty_df = pd.DataFrame()\n", " \n", " # We can't proceed with linking if either trait or gene data is missing\n", " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n", " 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=True, # Data is unusable if we're missing components\n", " df=empty_df, # Empty dataframe for metadata\n", " note=\"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\n", " )" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }