{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f396a6b4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:17:15.466030Z", "iopub.status.busy": "2025-03-25T05:17:15.465929Z", "iopub.status.idle": "2025-03-25T05:17:15.625309Z", "shell.execute_reply": "2025-03-25T05:17:15.624959Z" } }, "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 = \"Gastroesophageal_reflux_disease_(GERD)\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e5e4c7c6", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "493e4779", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:17:15.626740Z", "iopub.status.busy": "2025-03-25T05:17:15.626601Z", "iopub.status.idle": "2025-03-25T05:17:16.756531Z", "shell.execute_reply": "2025-03-25T05:17:16.756149Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found potential match: TCGA_Stomach_Cancer_(STAD) (score: 1)\n", "Selected directory: TCGA_Stomach_Cancer_(STAD)\n", "Clinical file: TCGA.STAD.sampleMap_STAD_clinicalMatrix\n", "Genetic file: TCGA.STAD.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['CDE_ID_3226963', '_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_surgery_locoregional_procedure', 'additional_surgery_metastatic_procedure', 'age_at_initial_pathologic_diagnosis', 'anatomic_neoplasm_subdivision', 'antireflux_treatment', 'antireflux_treatment_type', 'barretts_esophagus', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'city_of_procurement', 'country_of_procurement', 'days_to_additional_surgery_locoregional_procedure', 'days_to_additional_surgery_metastatic_procedure', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_after_initial_treatment', 'family_history_of_stomach_cancer', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'h_pylori_infection', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'longest_dimension', 'lost_follow_up', 'lymph_node_examined_count', 'neoplasm_histologic_grade', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_after_initial_treatment', 'number_of_lymphnodes_positive_by_he', 'number_of_relatives_with_stomach_cancer', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_death_reason', 'patient_id', 'person_neoplasm_cancer_status', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'progression_determined_by', 'radiation_therapy', 'reflux_history', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_STAD_mutation', '_GENOMIC_ID_TCGA_STAD_mutation_curated_broad_gene', '_GENOMIC_ID_TCGA_STAD_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_STAD_exp_GA_exon', '_GENOMIC_ID_TCGA_STAD_exp_HiSeqV2', '_GENOMIC_ID_TCGA_STAD_hMethyl27', '_GENOMIC_ID_TCGA_STAD_mutation_bcm_gene', '_GENOMIC_ID_TCGA_STAD_gistic2', '_GENOMIC_ID_TCGA_STAD_hMethyl450', '_GENOMIC_ID_data/public/TCGA/STAD/miRNA_GA_gene', '_GENOMIC_ID_TCGA_STAD_RPPA', '_GENOMIC_ID_TCGA_STAD_miRNA_HiSeq', '_GENOMIC_ID_TCGA_STAD_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_STAD_gistic2thd', '_GENOMIC_ID_TCGA_STAD_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_STAD_exp_HiSeq_exon', '_GENOMIC_ID_TCGA_STAD_exp_GA', '_GENOMIC_ID_TCGA_STAD_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_STAD_mutation_broad_gene', '_GENOMIC_ID_TCGA_STAD_PDMRNAseq', '_GENOMIC_ID_data/public/TCGA/STAD/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_STAD_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_STAD_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_STAD_exp_HiSeq', '_GENOMIC_ID_TCGA_STAD_miRNA_GA']\n", "\n", "Clinical data shape: (580, 107)\n", "Genetic data shape: (20530, 450)\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# 1. Find the most relevant directory for Gastroesophageal reflux disease (GERD)\n", "subdirectories = os.listdir(tcga_root_dir)\n", "target_trait = trait.lower().replace(\"_\", \" \") # Convert to lowercase for case-insensitive matching\n", "\n", "# Define key terms relevant to GERD\n", "key_terms = [\"esophageal\", \"stomach\", \"gastro\", \"reflux\", \"gastric\", \"esophagus\"]\n", "\n", "# Start with no match, then find the best match based on similarity to target trait\n", "best_match = None\n", "best_match_score = 0\n", "min_threshold = 1 # Require at least 1 matching term\n", "\n", "for subdir in subdirectories:\n", " if not os.path.isdir(os.path.join(tcga_root_dir, subdir)) or subdir.startswith('.'):\n", " continue\n", " \n", " subdir_lower = subdir.lower()\n", " \n", " # Check for exact matches\n", " if target_trait in subdir_lower:\n", " best_match = subdir\n", " print(f\"Found exact match: {subdir}\")\n", " break\n", " \n", " # Calculate a score based on key terms\n", " score = 0\n", " for term in key_terms:\n", " if term in subdir_lower:\n", " score += 1\n", " \n", " # Check for partial matches with threshold\n", " if score > best_match_score and score >= min_threshold:\n", " best_match_score = score\n", " best_match = subdir\n", " print(f\"Found potential match: {subdir} (score: {score})\")\n", "\n", "# Use the best match if found\n", "if best_match:\n", " print(f\"Selected directory: {best_match}\")\n", " \n", " # 2. Get the clinical and genetic data file paths\n", " cohort_dir = os.path.join(tcga_root_dir, best_match)\n", " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", " \n", " print(f\"Clinical file: {os.path.basename(clinical_file_path)}\")\n", " print(f\"Genetic file: {os.path.basename(genetic_file_path)}\")\n", " \n", " # 3. Load the data files\n", " clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", " genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n", " \n", " # 4. Print clinical data columns for inspection\n", " print(\"\\nClinical data columns:\")\n", " print(clinical_df.columns.tolist())\n", " \n", " # Print basic information about the datasets\n", " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n", " print(f\"Genetic data shape: {genetic_df.shape}\")\n", " \n", " # Check if we have both gene and trait data\n", " is_gene_available = genetic_df.shape[0] > 0\n", " is_trait_available = clinical_df.shape[0] > 0\n", " \n", "else:\n", " print(f\"No suitable directory found for {trait}. This trait may not be directly represented in the TCGA dataset.\")\n", " is_gene_available = False\n", " is_trait_available = False\n", "\n", "# Record the data availability\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# Exit if no suitable directory was found\n", "if not best_match:\n", " print(\"Skipping this trait as no suitable data was found.\")\n" ] }, { "cell_type": "markdown", "id": "85a22f61", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "b9d7a08f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:17:16.757966Z", "iopub.status.busy": "2025-03-25T05:17:16.757859Z", "iopub.status.idle": "2025-03-25T05:17:16.768212Z", "shell.execute_reply": "2025-03-25T05:17:16.767915Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age column previews:\n", "{'age_at_initial_pathologic_diagnosis': [70.0, 51.0, 51.0, 62.0, 52.0], 'days_to_birth': [nan, nan, -18698.0, -22792.0, -19014.0]}\n", "\n", "Gender column previews:\n", "{'gender': ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']}\n" ] } ], "source": [ "# Identify columns related to age\n", "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n", "\n", "# Identify columns related to gender\n", "candidate_gender_cols = ['gender']\n", "\n", "# Load the clinical data if not already loaded\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, \"TCGA_Stomach_Cancer_(STAD)\"))\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Preview age-related columns\n", "age_preview = {}\n", "for col in candidate_age_cols:\n", " if col in clinical_df.columns:\n", " age_preview[col] = clinical_df[col].head(5).tolist()\n", "\n", "# Preview gender-related columns\n", "gender_preview = {}\n", "for col in candidate_gender_cols:\n", " if col in clinical_df.columns:\n", " gender_preview[col] = clinical_df[col].head(5).tolist()\n", "\n", "# Display the previews\n", "print(\"Age column previews:\")\n", "print(age_preview)\n", "print(\"\\nGender column previews:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "ad6deec5", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "25cbc71b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:17:16.769371Z", "iopub.status.busy": "2025-03-25T05:17:16.769271Z", "iopub.status.idle": "2025-03-25T05:17:16.771917Z", "shell.execute_reply": "2025-03-25T05:17:16.771643Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "import numpy as np\n", "\n", "# Selecting the most appropriate columns for age and gender\n", "age_cols_data = {'age_at_initial_pathologic_diagnosis': [70.0, 51.0, 51.0, 62.0, 52.0], \n", " 'days_to_birth': [np.nan, np.nan, -18698.0, -22792.0, -19014.0]}\n", "\n", "gender_cols_data = {'gender': ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']}\n", "\n", "# Selecting age column\n", "# The 'age_at_initial_pathologic_diagnosis' column has more non-null values and \n", "# represents age directly rather than requiring conversion\n", "age_col = 'age_at_initial_pathologic_diagnosis' if 'age_at_initial_pathologic_diagnosis' in age_cols_data else None\n", "\n", "# Selecting gender column\n", "# The 'gender' column contains standard gender values\n", "gender_col = 'gender' if 'gender' in gender_cols_data else None\n", "\n", "# Print the selected columns\n", "print(f\"Selected age column: {age_col}\")\n", "print(f\"Selected gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "b6aada2e", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "4578feef", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:17:16.773345Z", "iopub.status.busy": "2025-03-25T05:17:16.773037Z", "iopub.status.idle": "2025-03-25T05:17:59.974720Z", "shell.execute_reply": "2025-03-25T05:17:59.974349Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/gene_data/TCGA.csv\n", "Gene expression data shape after normalization: (19848, 450)\n", "Clinical data saved to ../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/clinical_data/TCGA.csv\n", "Clinical data shape: (580, 3)\n", "Number of samples in clinical data: 580\n", "Number of samples in genetic data: 450\n", "Number of common samples: 450\n", "Linked data shape: (450, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (450, 19851)\n", "For the feature 'Gastroesophageal_reflux_disease_(GERD)', the least common label is '0' with 35 occurrences. This represents 7.78% of the dataset.\n", "The distribution of the feature 'Gastroesophageal_reflux_disease_(GERD)' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 58.0\n", " 50% (Median): 67.0\n", " 75%: 73.0\n", "Min: 30.0\n", "Max: 90.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 159 occurrences. This represents 35.33% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/TCGA.csv\n", "Preprocessing completed.\n" ] } ], "source": [ "# Step 1: Extract and standardize clinical features\n", "# Create clinical features dataframe with trait (Canavan Disease) using patient IDs\n", "clinical_features = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=trait, \n", " age_col=age_col, \n", " gender_col=gender_col\n", ")\n", "\n", "# Step 2: Normalize gene symbols in the gene expression data\n", "# The gene symbols in TCGA genetic data are already standardized, but we'll normalize them for consistency\n", "normalized_gene_df = normalize_gene_symbols_in_index(genetic_df)\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_df.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "print(f\"Gene expression data shape after normalization: {normalized_gene_df.shape}\")\n", "\n", "# Step 3: Link clinical and genetic data\n", "# Transpose genetic data to have samples as rows and genes as columns\n", "genetic_df_t = normalized_gene_df.T\n", "# Save the clinical data for reference\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", "print(f\"Clinical data shape: {clinical_features.shape}\")\n", "\n", "# Verify common indices between clinical and genetic data\n", "clinical_indices = set(clinical_features.index)\n", "genetic_indices = set(genetic_df_t.index)\n", "common_indices = clinical_indices.intersection(genetic_indices)\n", "print(f\"Number of samples in clinical data: {len(clinical_indices)}\")\n", "print(f\"Number of samples in genetic data: {len(genetic_indices)}\")\n", "print(f\"Number of common samples: {len(common_indices)}\")\n", "\n", "# Link the data by using the common indices\n", "linked_data = pd.concat([clinical_features.loc[list(common_indices)], genetic_df_t.loc[list(common_indices)]], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# Step 4: Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait_col=trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# Step 5: Determine whether the trait and demographic features are severely biased\n", "trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait)\n", "\n", "# Step 6: Conduct final quality validation and save information\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=True,\n", " is_biased=trait_biased,\n", " df=linked_data,\n", " note=f\"Dataset contains TCGA glioma and brain tumor samples with gene expression and clinical information for {trait}.\"\n", ")\n", "\n", "# Step 7: Save linked data if 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(\"Dataset deemed not usable based on validation criteria. Data not saved.\")\n", "\n", "print(\"Preprocessing completed.\")" ] } ], "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 }