{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "521f0a75", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:51.697314Z", "iopub.status.busy": "2025-03-25T05:09:51.697206Z", "iopub.status.idle": "2025-03-25T05:09:51.867318Z", "shell.execute_reply": "2025-03-25T05:09:51.866954Z" } }, "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 = \"Epilepsy\"\n", "cohort = \"GSE64123\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Epilepsy\"\n", "in_cohort_dir = \"../../input/GEO/Epilepsy/GSE64123\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Epilepsy/GSE64123.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Epilepsy/gene_data/GSE64123.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Epilepsy/clinical_data/GSE64123.csv\"\n", "json_path = \"../../output/preprocess/Epilepsy/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6ab49d76", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "614db7bd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:51.868824Z", "iopub.status.busy": "2025-03-25T05:09:51.868674Z", "iopub.status.idle": "2025-03-25T05:09:51.991008Z", "shell.execute_reply": "2025-03-25T05:09:51.990645Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Human embryonic stem cell based neuro-developmental toxicity assay: response to valproic acid and carbamazepine exposure\"\n", "!Series_summary\t\"Here we studied the effects of anticonvulsant drug exposure in a human embryonic stem cell (hESC) based neuro- developmental toxicity test (hESTn). During neural differentiation the cells were exposed, for either 1 or 7 days, to non-cytotoxic concentration ranges of valproic acid (VPA) or carbamazepine (CBZ), anti-epileptic drugs known to cause neurodevelopmental toxicity.\"\n", "!Series_overall_design\t\"93 samples (multiple time points, multiple exposures, multiple concentrations, multiple replicates)\"\n", "Sample Characteristics Dictionary:\n", "{0: ['time: 0 days', 'time: 1 days', 'time: 4 days', 'time: 7 days', 'time: 9 days', 'time: 11 days'], 1: ['exposure: unexposed', 'exposure: DMSO', 'exposure: carbamazepine', 'exposure: valproic acid'], 2: ['concentration: 0 mM', 'concentration: 0.25%', 'concentration: 0.033 mM', 'concentration: 0.1 mM', 'concentration: 0.33 mM', 'concentration: 1 mM']}\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": "3c808071", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b12b20b5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:51.992234Z", "iopub.status.busy": "2025-03-25T05:09:51.992117Z", "iopub.status.idle": "2025-03-25T05:09:51.999685Z", "shell.execute_reply": "2025-03-25T05:09:51.999434Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "import os\n", "from typing import Optional, Callable, Dict, Any\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset appears to be about gene expression during neural differentiation\n", "# and the effects of drug exposure, so it likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking at sample characteristics dictionary, we don't find direct trait (epilepsy) information\n", "# The dataset is about effects of anticonvulsant drugs on neural development, not patients with epilepsy\n", "trait_row = None # No epilepsy trait data available\n", "\n", "# Age data is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender data is not available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert epilepsy trait value to binary (0/1)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.lower().strip()\n", " \n", " if value in ['yes', 'epilepsy', 'epileptic', 'seizure disorder', 'true', '1']:\n", " return 1\n", " elif value in ['no', 'control', 'healthy', 'normal', 'false', '0']:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age value to continuous numeric value\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender value to binary (0=female, 1=male)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.lower().strip()\n", " \n", " if value in ['female', 'f', 'woman', 'girl']:\n", " return 0\n", " elif value in ['male', 'm', 'man', 'boy']:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate 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", "# Skip this step as trait_row is None (no clinical data available for our specific trait of interest)\n" ] }, { "cell_type": "markdown", "id": "cc66cc7c", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "46505f3c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:52.000839Z", "iopub.status.busy": "2025-03-25T05:09:52.000732Z", "iopub.status.idle": "2025-03-25T05:09:52.213347Z", "shell.execute_reply": "2025-03-25T05:09:52.213015Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Epilepsy/GSE64123/GSE64123_family.soft.gz\n", "Matrix file: ../../input/GEO/Epilepsy/GSE64123/GSE64123_series_matrix.txt.gz\n", "Found the matrix table marker in the file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (18909, 93)\n", "First 20 gene/probe identifiers:\n", "['100009676_at', '10000_at', '10001_at', '10002_at', '10003_at', '100048912_at', '100049716_at', '10004_at', '10005_at', '10006_at', '10007_at', '10008_at', '100093630_at', '10009_at', '1000_at', '100101467_at', '100101938_at', '10010_at', '100113407_at', '10011_at']\n" ] } ], "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": "fef043f5", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "c9e1e498", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:52.214553Z", "iopub.status.busy": "2025-03-25T05:09:52.214426Z", "iopub.status.idle": "2025-03-25T05:09:52.216377Z", "shell.execute_reply": "2025-03-25T05:09:52.216086Z" } }, "outputs": [], "source": [ "# Analyzing the gene identifiers in the provided list\n", "# The format \"100009676_at\" suggests these are Affymetrix microarray probe set IDs\n", "# These are not standard human gene symbols and need to be mapped to gene symbols\n", "# Affymetrix IDs typically end with \"_at\" and need conversion to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "07167694", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "6f6add7b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:52.217408Z", "iopub.status.busy": "2025-03-25T05:09:52.217297Z", "iopub.status.idle": "2025-03-25T05:09:54.309458Z", "shell.execute_reply": "2025-03-25T05:09:54.309101Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'SPOT_ID', 'Description']\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'SPOT_ID': ['1', '10', '100', '1000', '10000'], 'Description': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\n", "\n", "Sample of Description column (first 5 rows):\n", "Row 0: alpha-1-B glycoprotein\n", "Row 1: N-acetyltransferase 2 (arylamine N-acetyltransferase)\n", "Row 2: adenosine deaminase\n", "Row 3: cadherin 2, type 1, N-cadherin (neuronal)\n", "Row 4: v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)\n" ] } ], "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", "# Based on the preview, 'ID' appears to be the probe ID and 'Description' contains gene names\n", "# Display more samples from the Description column to better understand the format\n", "print(\"\\nSample of Description column (first 5 rows):\")\n", "if 'Description' in gene_annotation.columns:\n", " for i in range(min(5, len(gene_annotation))):\n", " print(f\"Row {i}: {gene_annotation['Description'].iloc[i]}\")\n" ] }, { "cell_type": "markdown", "id": "9bcf009c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "f3022573", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:54.310782Z", "iopub.status.busy": "2025-03-25T05:09:54.310644Z", "iopub.status.idle": "2025-03-25T05:09:54.622213Z", "shell.execute_reply": "2025-03-25T05:09:54.621872Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Example probe IDs in gene expression data: ['100009676_at', '10000_at', '10001_at', '10002_at', '10003_at']\n", "Example IDs in annotation data: ['1_at', '10_at', '100_at', '1000_at', '10000_at']\n", "Gene mapping preview:\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'Gene': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\n", "Shape of gene mapping dataframe: (18876, 2)\n", "Number of probes in gene expression data that can be mapped: 18876\n", "Gene expression data after mapping:\n", "Shape of gene expression data: (2024, 93)\n", "First few gene symbols:\n", "['A-', 'A-2', 'A-52', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1', 'A10']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after normalizing gene symbols:\n", "Shape of gene expression data: (1168, 93)\n", "First few normalized gene symbols:\n", "['A1BG', 'A4GALT', 'AAA1', 'ABCC11', 'ABCD1', 'ABCE1', 'ABI3', 'ABO', 'ACSM3', 'ADAT2']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Epilepsy/gene_data/GSE64123.csv\n" ] } ], "source": [ "# Analyze the identifiers in gene annotation and gene expression data\n", "print(\"Example probe IDs in gene expression data:\", gene_data.index[:5].tolist())\n", "print(\"Example IDs in annotation data:\", gene_annotation['ID'][:5].tolist())\n", "\n", "# 1. Determine which columns to use for mapping\n", "# The gene annotation 'ID' column contains probe IDs like \"1_at\"\n", "# The gene expression data index contains probes like \"100009676_at\"\n", "# The 'Description' column contains gene symbols/descriptions\n", "\n", "# 2. Create the gene mapping dataframe\n", "# Extract the relevant columns for mapping\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Description')\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping, n=5))\n", "print(f\"Shape of gene mapping dataframe: {gene_mapping.shape}\")\n", "\n", "# Count how many probes can be mapped to the gene expression data\n", "common_probes = set(gene_data.index).intersection(set(gene_mapping['ID']))\n", "print(f\"Number of probes in gene expression data that can be mapped: {len(common_probes)}\")\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene-level expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(\"Gene expression data after mapping:\")\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Apply standardization to gene symbols\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(\"\\nGene expression data after normalizing gene symbols:\")\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Save the processed gene expression data\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" ] }, { "cell_type": "markdown", "id": "bde555d2", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "439de11b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:54.623604Z", "iopub.status.busy": "2025-03-25T05:09:54.623477Z", "iopub.status.idle": "2025-03-25T05:09:54.758215Z", "shell.execute_reply": "2025-03-25T05:09:54.757865Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (1168, 93)\n", "Gene data shape after normalization: (1168, 93)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Epilepsy/gene_data/GSE64123.csv\n", "No trait data (Epilepsy) available in this dataset based on previous analysis.\n", "Cannot proceed with data linking due to missing trait or gene data.\n", "Abnormality detected in the cohort: GSE64123. Preprocessing failed.\n" ] } ], "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 Epilepsy data available\n", "# age_row = None\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(\"No trait data (Epilepsy) 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 GBM cell cultures, but no epilepsy phenotype information.\"\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=\"Missing essential data components for linking: dataset contains gene expression data from GBM cell cultures, but no epilepsy phenotype information.\"\n", " )" ] } ], "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 }