{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "241024f9", "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 = \"Thyroid_Cancer\"\n", "cohort = \"GSE80022\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Thyroid_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Thyroid_Cancer/GSE80022\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Thyroid_Cancer/GSE80022.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Thyroid_Cancer/gene_data/GSE80022.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Thyroid_Cancer/clinical_data/GSE80022.csv\"\n", "json_path = \"../../output/preprocess/Thyroid_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "02c8e61a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "87dbc7c9", "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": "c37ad651", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "8a2b59a7", "metadata": {}, "outputs": [], "source": [ "# Functions to convert clinical features\n", "def convert_trait(val):\n", " \"\"\"Convert trait data to binary format (0 = No thyroid cancer, 1 = Thyroid cancer)\"\"\"\n", " if val is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in val:\n", " val = val.split(':', 1)[1].strip()\n", " \n", " # GOT1 is small intestine tumor, GOT2 is thyroid cancer (medullary thyroid carcinoma)\n", " if 'GOT2' in val:\n", " return 1 # Thyroid cancer\n", " elif 'GOT1' in val:\n", " return 0 # Not thyroid cancer\n", " else:\n", " return None\n", "\n", "def convert_age(val):\n", " \"\"\"Process age data - Not available in this dataset\"\"\"\n", " return None\n", "\n", "def convert_gender(val):\n", " \"\"\"Process gender data - Not available in this dataset\"\"\"\n", " return None\n", "\n", "# Determine data availability\n", "# 1. Gene Expression Data: Sample characteristics and background info suggest this is gene expression data\n", "is_gene_available = True # This is transcriptomic profiling data\n", "\n", "# 2. Clinical features availability\n", "# 2.1 Trait data - Xenograft tissue type is in row 1\n", "trait_row = 1 # GOT1 or GOT2\n", "\n", "# 2.2 Age data - Not available\n", "age_row = None\n", "\n", "# 2.3 Gender data - Not available\n", "gender_row = None\n", "\n", "# 3. Save metadata for initial filtering\n", "is_trait_available = trait_row is not None\n", "# Initial validation - just check if the dataset contains needed data\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 (only if trait_row is not None)\n", "# Check if the clinical data file exists before attempting to read it\n", "clinical_file_path = f\"{in_cohort_dir}/clinical_data.csv\"\n", "if trait_row is not None and os.path.exists(clinical_file_path):\n", " # Load clinical data\n", " clinical_data = pd.read_csv(clinical_file_path, index_col=0)\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 processed clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of clinical data:\")\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)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(f\"Clinical data file not found at {clinical_file_path}\")\n", " print(\"Skipping clinical feature extraction step.\")\n" ] }, { "cell_type": "markdown", "id": "3b7b8f09", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "a7999187", "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", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for line in file:\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " break\n", " \n", " if found_marker:\n", " print(\"Found the matrix table marker in the file.\")\n", " else:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " \n", " # Try to extract gene data from the matrix file\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", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " is_gene_available = False\n", " \n", " # Try to diagnose the file format\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if i < 10: # Print first 10 lines to diagnose\n", " print(f\"Line {i}: {line.strip()[:100]}...\") # Print first 100 chars of each line\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", "\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n" ] }, { "cell_type": "markdown", "id": "38f95050", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "5126acc9", "metadata": {}, "outputs": [], "source": [ "# The identifiers start with ILMN_, which indicates Illumina probe IDs, not human gene symbols\n", "# These are microarray probe identifiers that need to be mapped to human gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "fb6a4084", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "84b7c178", "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=5))\n", "\n", "# Get a more complete view to understand the annotation structure\n", "print(\"\\nComplete sample of a few rows:\")\n", "print(gene_annotation.iloc[:3].to_string())\n", "\n", "# Check for columns that might contain gene information\n", "potential_gene_columns = [col for col in gene_annotation.columns if \n", " any(term in col.upper() for term in [\"GENE\", \"SYMBOL\", \"NAME\", \"ID\"])]\n", "print(f\"\\nPotential gene-related columns: {potential_gene_columns}\")\n", "\n", "# Correctly identify the columns for probe ID and gene symbols\n", "gene_id_col = 'ID' # This is the probe identifier column\n", "gene_symbol_col = 'Symbol' # This is the correct gene symbol column name from the preview\n", "\n", "# Verify columns exist before mapping\n", "if gene_id_col in gene_annotation.columns and gene_symbol_col in gene_annotation.columns:\n", " # Create the mapping using the library function\n", " mapping_data = get_gene_mapping(gene_annotation, gene_id_col, gene_symbol_col)\n", " \n", " # Print sample of the mapping to confirm\n", " print(\"\\nSample of probe ID to gene symbol mappings:\")\n", " print(mapping_data.head(10))\n", " \n", " # Check the size of the mapping data\n", " print(f\"\\nTotal number of probe-to-gene mappings: {len(mapping_data)}\")\n", "else:\n", " missing_cols = []\n", " if gene_id_col not in gene_annotation.columns:\n", " missing_cols.append(gene_id_col)\n", " if gene_symbol_col not in gene_annotation.columns:\n", " missing_cols.append(gene_symbol_col)\n", " print(f\"\\nError: The following columns are missing from the annotation data: {missing_cols}\")\n" ] }, { "cell_type": "markdown", "id": "1232d1ad", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "8ab63eb8", "metadata": {}, "outputs": [], "source": [ "# Extract gene expression data from the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_expression = get_genetic_data(matrix_file)\n", "\n", "# Extract gene annotation from the SOFT file\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# The mapping will use 'ID' (probe identifiers) to 'Symbol' (gene symbols)\n", "mapping_data = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", "\n", "# Check the data before mapping\n", "print(f\"Gene expression data shape: {gene_expression.shape}\")\n", "print(f\"Mapping data shape: {mapping_data.shape}\")\n", "\n", "# Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_expression, mapping_data)\n", "\n", "# Check the resulting gene expression data\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "\n", "# Preview the first few rows of the gene data\n", "print(\"Preview of mapped gene expression data:\")\n", "print(gene_data.head())\n", "\n", "# Check for non-human entries in the mapped gene data\n", "non_human_genes = [gene for gene in gene_data.index[:20] if not isinstance(gene, str) or \n", " 'phage' in gene.lower() or ':' in gene or len(gene) < 2]\n", "if non_human_genes:\n", " print(f\"Note: Found non-human gene entries: {non_human_genes}\")\n" ] }, { "cell_type": "markdown", "id": "ca3d47f9", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "15cad689", "metadata": {}, "outputs": [], "source": [ "```python\n", "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Create directory for gene data file\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use gene_data from the previous step instead of trying to load it\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", " 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. Extract clinical features using the correct indices from Step 2\n", "try:\n", " # Redefine the conversion functions from Step 2\n", " def convert_trait(val):\n", " \"\"\"Convert trait data to binary format (0 = No thyroid cancer, 1 = Thyroid cancer)\"\"\"\n", " if val is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in val:\n", " val = val.split(':', 1)[1].strip()\n", " \n", " # GOT1 is small intestine tumor, GOT2 is thyroid cancer (medullary thyroid carcinoma)\n", " if 'GOT2' in val:\n", " return 1 # Thyroid cancer\n", " elif 'GOT1' in val:\n", " return 0 # Not thyroid cancer\n", " else:\n", " return None\n", "\n", " def convert_age(val):\n", " \"\"\"Process age data - Not available in this dataset\"\"\"\n", " return None\n", "\n", " def convert_gender(val):\n", " \"\"\"Process gender data - Not available in this dataset\"\"\"\n", " return None\n", " \n", " # Get the original clinical data\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 with correct indices from Step 2\n", " trait_row = 1 # From Step 2\n", " age_row = None # From Step 2\n", " gender_row = None # From Step 2\n", " \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", " 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", " \n", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\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): {normalized_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(normalized_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, normalized_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 GOT1 (small intestine neuroendocrine tumor) and GOT2 (medullary thyroid carcinoma) xenografts in mice.\"\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", " # 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=p\n" ] }, { "cell_type": "markdown", "id": "41085f3b", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "7e72efe3", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Load the gene data that was saved in the previous step\n", " gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", " print(f\"Loaded gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to gene symbols\n", " gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error loading or normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data with correct row indices\n", "try:\n", " # Load the original clinical data (from Step 1)\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 with correct indices from Step 2\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=2, # Correct value from Step 2\n", " convert_trait=convert_trait,\n", " age_row=1,\n", " convert_age=convert_age,\n", " gender_row=0,\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", " \n", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\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 follicular thyroid cancer and follicular thyroid adenoma tissue samples.\"\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", " # 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=pd.DataFrame(), # Empty dataframe for metadata\n", " note=\"Missing essential data components for linking (trait data or gene expression data).\"\n", " )" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }