{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "78b3d1f8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:49.924018Z", "iopub.status.busy": "2025-03-25T07:18:49.923774Z", "iopub.status.idle": "2025-03-25T07:18:50.086977Z", "shell.execute_reply": "2025-03-25T07:18:50.086627Z" } }, "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 = \"Kidney_Clear_Cell_Carcinoma\"\n", "cohort = \"GSE95425\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_Clear_Cell_Carcinoma/GSE95425\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/GSE95425.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE95425.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/GSE95425.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6f37e2f9", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "eb6d3bf3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:50.088388Z", "iopub.status.busy": "2025-03-25T07:18:50.088250Z", "iopub.status.idle": "2025-03-25T07:18:50.167351Z", "shell.execute_reply": "2025-03-25T07:18:50.167010Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Cell-type specific gene programs of the normal human nephron define kidney cancer subtypes\"\n", "!Series_summary\t\"Comprehensive transcriptome studies of cancers often rely on corresponding normal tissue samples to serve as a transcriptional reference. In this study we performed in-depth analyses of normal kidney tissue transcriptomes from TCGA and demonstrate that the histological variability in cellularity, inherent in the kidney architecture, lead to considerable transcriptional differences between samples. This should be considered when comparing expression profiles of normal and cancerous kidney tissues. We exploited these differences to define renal cell-specific gene signatures and used these as framework to analyze renal cell carcinoma (RCC) ontogeny. Chromophobe RCCs express FOXI1-driven genes that define collecting duct intercalated cells whereas HNF-regulated genes, specific for proximal tubule cells, are an integral part of clear cell and papillary RCC transcriptomes. These networks may be used as framework for understanding the interplay between genomic changes in RCC subtypes and the lineage-defining regulatory machinery of their non-neoplastic counterparts.\"\n", "!Series_overall_design\t\"Samples from different parts of the kidneys were procured using core-sampling from approximately 10 mm thick sections obtained from nephrectomized patients in surgery for renal neoplasms. Sampling was performed in the part of the kidney that was farthest from the tumor. Sections were thereafter embedded and hematoxylin-eosin stained allowing for approximation of the respective site in kidney from which the sample was obtained. In all cases a histologically normal kidney histology was confirmed. In all, 53 samples from 5 different renal specimens were included in the analysis.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient id: R099', 'patient id: R116', 'patient id: R127', 'patient id: R134', 'patient id: R164'], 1: ['patient type: Normal kidney tissue'], 2: ['sampling depth: cortex', 'sampling depth: cortex/medulla', 'sampling depth: medulla']}\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": "fba3ecda", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9862469b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:50.168621Z", "iopub.status.busy": "2025-03-25T07:18:50.168515Z", "iopub.status.idle": "2025-03-25T07:18:50.189930Z", "shell.execute_reply": "2025-03-25T07:18:50.189668Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# Examine the provided information to determine gene expression data availability\n", "is_gene_available = True # Dataset is likely to contain gene expression data based on the background info describing kidney tissue transcriptomes\n", "\n", "# Analyze sample characteristics dictionary to identify keys containing trait, age, and gender information\n", "trait_row = None # No specific trait info available for kidney cancer in the samples (all are normal tissues)\n", "age_row = None # No age information available\n", "gender_row = None # No gender information available\n", "\n", "# Define conversion functions (even though we don't have data for them, we define them for completeness)\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert trait values to binary format.\"\"\"\n", " if not value or \":\" not in value:\n", " return None\n", " \n", " val = value.split(\":\", 1)[1].strip().lower()\n", " \n", " # Since all samples are normal kidney tissue, there's no trait variation\n", " return None # No appropriate conversion possible\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age values to continuous format.\"\"\"\n", " if not value or \":\" not in value:\n", " return None\n", " \n", " val = value.split(\":\", 1)[1].strip()\n", " try:\n", " return float(val)\n", " except ValueError:\n", " return None\n", " \n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender values to binary format (0 for female, 1 for male).\"\"\"\n", " if not value or \":\" not in value:\n", " return None\n", " \n", " val = value.split(\":\", 1)[1].strip().lower()\n", " if val in [\"female\", \"f\"]:\n", " return 0\n", " elif val in [\"male\", \"m\"]:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Determine trait availability\n", "is_trait_available = False # Since trait_row is None, trait data is not available\n", "\n", "# Save metadata about the dataset using the validate_and_save_cohort_info function\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", "# Skip clinical feature extraction since trait_row is None\n" ] }, { "cell_type": "markdown", "id": "e1bf0923", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "01050da1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:50.190896Z", "iopub.status.busy": "2025-03-25T07:18:50.190796Z", "iopub.status.idle": "2025-03-25T07:18:50.331752Z", "shell.execute_reply": "2025-03-25T07:18:50.331382Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n", "Successfully extracted gene data with 27367 rows\n", "First 20 gene IDs:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228',\n", " 'ILMN_1651229', 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651236',\n", " 'ILMN_1651238', 'ILMN_1651253', 'ILMN_1651254', 'ILMN_1651259',\n", " 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278',\n", " 'ILMN_1651281', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286'],\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": "dde104fd", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "f4452040", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:50.332987Z", "iopub.status.busy": "2025-03-25T07:18:50.332878Z", "iopub.status.idle": "2025-03-25T07:18:50.334633Z", "shell.execute_reply": "2025-03-25T07:18:50.334367Z" } }, "outputs": [], "source": [ "# These identifiers are Illumina BeadChip IDs (ILMN_xxxxxxx), not human gene symbols\n", "# They need to be mapped to standard gene symbols for downstream analysis\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "2100bd2e", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a4e67c4e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:50.335681Z", "iopub.status.busy": "2025-03-25T07:18:50.335580Z", "iopub.status.idle": "2025-03-25T07:18:53.884021Z", "shell.execute_reply": "2025-03-25T07:18:53.883366Z" } }, "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 1498611 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 47323 out of 1498611\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "484e54e8", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "99181b3e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:53.885925Z", "iopub.status.busy": "2025-03-25T07:18:53.885803Z", "iopub.status.idle": "2025-03-25T07:18:54.621740Z", "shell.execute_reply": "2025-03-25T07:18:54.621088Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Identifying relevant columns for gene mapping...\n", "Creating gene mapping from ID to Symbol...\n", "Generated mapping data with 44837 entries\n", "First few rows of mapping data:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n", "Converting probe-level measurements to gene expression data...\n", "Successfully converted to gene expression data with 17999 genes\n", "First few gene symbols:\n", "['A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n", "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 17405 unique genes\n", "First few normalized gene symbols:\n", "['A1BG-AS1', 'A1CF', 'A2M', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AADAC']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE95425.csv\n" ] } ], "source": [ "# 1. Identify which columns in gene_annotation contain probe IDs and gene symbols\n", "print(\"Identifying relevant columns for gene mapping...\")\n", "\n", "# The gene expression data uses 'ILMN_xxxxxxx' IDs as shown in a previous step\n", "# From the gene_annotation preview, we see:\n", "# - 'ID' column contains the same ILMN IDs that match gene_data index\n", "# - 'Symbol' column contains gene symbols we want to map to\n", "\n", "# 2. Create gene mapping dataframe using the identified columns\n", "prob_col = 'ID' # Column containing probe IDs\n", "gene_col = 'Symbol' # Column containing gene symbols\n", "\n", "print(f\"Creating gene mapping from {prob_col} to {gene_col}...\")\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "print(f\"Generated mapping data with {len(mapping_data)} entries\")\n", "print(\"First few rows of mapping data:\")\n", "print(preview_df(mapping_data))\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene-level expression\n", "print(\"Converting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "\n", "print(f\"Successfully converted to gene expression data with {len(gene_data)} genes\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Optional: normalize gene symbols to handle synonyms\n", "print(\"Normalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {len(gene_data)} unique genes\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Save the gene data to file\n", "out_gene_dir = os.path.dirname(out_gene_data_file)\n", "os.makedirs(out_gene_dir, 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": "ee588a04", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "1181cbf1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:54.623683Z", "iopub.status.busy": "2025-03-25T07:18:54.623553Z", "iopub.status.idle": "2025-03-25T07:18:55.190520Z", "shell.execute_reply": "2025-03-25T07:18:55.189883Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "After normalization: 17405 unique gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/GSE95425.csv\n", "\n", "Checking trait availability from previous analysis...\n", "Clinical trait data not available, skipping clinical feature extraction.\n", "\n", "Linking clinical and genetic data...\n", "Cannot link data: clinical or genetic data is missing\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE95425. Preprocessing failed.\n", "Dataset not usable for Kidney_Clear_Cell_Carcinoma association studies. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "try:\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {len(normalized_gene_data.index)} unique gene symbols\")\n", " \n", " # Save the normalized gene data (this was already done in Step 6, but we'll ensure it's saved)\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 expression data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene symbols: {e}\")\n", " normalized_gene_data = gene_data # Use original data if normalization fails\n", "\n", "# Respect the determination made in Step 2 that trait data is not available\n", "print(\"\\nChecking trait availability from previous analysis...\")\n", "# We previously determined trait_row is None and is_trait_available is False\n", "if trait_row is None:\n", " print(\"Clinical trait data not available, skipping clinical feature extraction.\")\n", " is_trait_available = False\n", " clinical_df = None\n", "else:\n", " # This block would execute if trait data was available, which it isn't in this case\n", " print(\"Extracting clinical features...\")\n", " try:\n", " 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", " print(f\"Clinical data extracted with shape: {clinical_df.shape}\")\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " is_trait_available = True\n", " except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n", " is_trait_available = False\n", " clinical_df = None\n", "\n", "# 2. Link clinical and genetic data if available\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if clinical_df is not None and not normalized_gene_data.empty:\n", " # Print sample IDs from both datasets for debugging\n", " print(\"First few clinical sample columns:\", list(clinical_df.columns)[:5])\n", " print(\"First few genetic sample columns:\", list(normalized_gene_data.columns)[:5])\n", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Check if we have at least one sample with trait value\n", " trait_count = linked_data[trait].count()\n", " print(f\"Number of samples with trait values: {trait_count}\")\n", " \n", " if trait_count > 0:\n", " # 3. Handle missing values systematically\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, data shape: {linked_data.shape}\")\n", " \n", " # Check if we still have samples after missing value handling\n", " if linked_data.shape[0] > 0:\n", " # 4. Determine whether the trait and demographic features are biased\n", " print(\"\\nChecking for bias in features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " else:\n", " print(\"Error: All samples were removed during missing value handling.\")\n", " is_biased = True\n", " else:\n", " print(\"No samples have valid trait values. Dataset cannot be used.\")\n", " is_biased = True\n", " else:\n", " print(\"Cannot link data: clinical or genetic data is missing\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " \n", "except Exception as e:\n", " print(f\"Error in linking clinical and genetic data: {e}\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 5. Final quality validation\n", "print(\"\\nPerforming final validation...\")\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 if 'is_biased' in locals() else True,\n", " df=linked_data if 'linked_data' in locals() and not linked_data.empty else pd.DataFrame(),\n", " note=\"Dataset contains gene expression data from kidney tissue samples but lacks trait information needed for association studies.\"\n", ")\n", "\n", "# 6. Save linked data if usable\n", "if is_usable and 'linked_data' in locals() and not linked_data.empty:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Dataset 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 }