{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "8ec6e2b6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:05:24.370947Z", "iopub.status.busy": "2025-03-25T07:05:24.370716Z", "iopub.status.idle": "2025-03-25T07:05:24.535141Z", "shell.execute_reply": "2025-03-25T07:05:24.534790Z" } }, "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 = \"Canavan_Disease\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Canavan_Disease/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Canavan_Disease/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Canavan_Disease/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Canavan_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "87ba3914", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e900b224", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:05:24.536532Z", "iopub.status.busy": "2025-03-25T07:05:24.536395Z", "iopub.status.idle": "2025-03-25T07:05:25.830861Z", "shell.execute_reply": "2025-03-25T07:05:25.830473Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found potential match: TCGA_Lower_Grade_Glioma_(LGG)\n", "Selected as best match: TCGA_Lower_Grade_Glioma_(LGG)\n", "Selected directory: TCGA_Lower_Grade_Glioma_(LGG)\n", "Clinical file: TCGA.LGG.sampleMap_LGG_clinicalMatrix\n", "Genetic file: TCGA.LGG.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['_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', 'animal_insect_allergy_history', 'animal_insect_allergy_types', 'asthma_history', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', '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', 'days_to_performance_status_assessment', 'eastern_cancer_oncology_group', 'eczema_history', 'family_history_of_cancer', 'family_history_of_primary_brain_tumor', 'first_diagnosis_age_asth_ecz_hay_fev_mold_dust', 'first_diagnosis_age_of_animal_insect_allergy', 'first_diagnosis_age_of_food_allergy', 'first_presenting_symptom', 'first_presenting_symptom_longest_duration', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'food_allergy_history', 'food_allergy_types', 'form_completion_date', 'gender', 'hay_fever_history', 'headache_history', 'histological_type', 'history_ionizing_rt_to_head', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'inherited_genetic_syndrome_found', 'inherited_genetic_syndrome_result', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'karnofsky_performance_score', 'laterality', 'ldh1_mutation_found', 'ldh1_mutation_test_method', 'ldh1_mutation_tested', 'longest_dimension', 'lost_follow_up', 'mental_status_changes', 'mold_or_dust_allergy_history', 'motor_movement_changes', 'neoplasm_histologic_grade', 'new_tumor_event_after_initial_treatment', 'oct_embedded', 'other_dx', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'preoperative_antiseizure_meds', 'preoperative_corticosteroids', 'primary_therapy_outcome_success', 'radiation_therapy', 'sample_type', 'sample_type_id', 'seizure_history', 'sensory_changes', 'shortest_dimension', 'supratentorial_localization', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_location', 'tumor_tissue_site', 'vial_number', 'visual_changes', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_LGG_mutation', '_GENOMIC_ID_TCGA_LGG_PDMRNAseq', '_GENOMIC_ID_TCGA_LGG_RPPA', '_GENOMIC_ID_TCGA_LGG_mutation_broad_gene', '_GENOMIC_ID_TCGA_LGG_gistic2', '_GENOMIC_ID_TCGA_LGG_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LGG_miRNA_HiSeq', '_GENOMIC_ID_TCGA_LGG_PDMarrayCNV', '_GENOMIC_ID_data/public/TCGA/LGG/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_LGG_mutation_curated_broad_gene', '_GENOMIC_ID_TCGA_LGG_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_LGG_hMethyl450_MethylMix', '_GENOMIC_ID_TCGA_LGG_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_LGG_mutation_bcm_gene', '_GENOMIC_ID_TCGA_LGG_hMethyl450', '_GENOMIC_ID_TCGA_LGG_PDMarray', '_GENOMIC_ID_TCGA_LGG_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LGG_G4502A_07_3', '_GENOMIC_ID_TCGA_LGG_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LGG_gistic2thd', '_GENOMIC_ID_TCGA_LGG_mutation_ucsc_maf_gene']\n", "\n", "Clinical data shape: (530, 113)\n", "Genetic data shape: (20530, 530)\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# 1. Find the most relevant directory for Canavan Disease\n", "subdirectories = os.listdir(tcga_root_dir)\n", "target_trait = trait.lower().replace(\"_\", \" \") # Convert to lowercase for case-insensitive matching\n", "\n", "# Search for related terms to Canavan Disease\n", "related_terms = [\"canavan\", \"leukodystrophy\", \"aspa\", \"neurological\", \"brain\", \"cns\", \"central nervous system\", \"glioma\"]\n", "matched_dir = None\n", "\n", "for subdir in subdirectories:\n", " subdir_lower = subdir.lower()\n", " # Check if any related term is in the directory name\n", " if any(term in subdir_lower for term in related_terms):\n", " matched_dir = subdir\n", " print(f\"Found potential match: {subdir}\")\n", " # Prioritize more specific matches\n", " if \"glioma\" in subdir_lower or \"gbm\" in subdir_lower:\n", " print(f\"Selected as best match: {subdir}\")\n", " matched_dir = subdir\n", " break\n", "\n", "# If we found a potential match, use it\n", "if matched_dir:\n", " print(f\"Selected directory: {matched_dir}\")\n", " \n", " # 2. Get the clinical and genetic data file paths\n", " cohort_dir = os.path.join(tcga_root_dir, matched_dir)\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}.\")\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 matched_dir:\n", " print(\"Skipping this trait as no suitable data was found.\")\n" ] }, { "cell_type": "markdown", "id": "5fb79a41", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "3503fa77", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:05:25.832225Z", "iopub.status.busy": "2025-03-25T07:05:25.832099Z", "iopub.status.idle": "2025-03-25T07:05:25.847133Z", "shell.execute_reply": "2025-03-25T07:05:25.846813Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [44.0, 50.0, 59.0, 56.0, 40.0], 'days_to_birth': [-16179.0, -18341.0, -21617.0, -20516.0, -14806.0], 'first_diagnosis_age_asth_ecz_hay_fev_mold_dust': [nan, nan, nan, nan, nan], 'first_diagnosis_age_of_animal_insect_allergy': [nan, nan, nan, nan, nan], 'first_diagnosis_age_of_food_allergy': [nan, nan, nan, nan, nan]}\n", "\n", "Gender columns preview:\n", "{'gender': ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Identify candidate columns for age and gender\n", "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth', 'first_diagnosis_age_asth_ecz_hay_fev_mold_dust', \n", " 'first_diagnosis_age_of_animal_insect_allergy', 'first_diagnosis_age_of_food_allergy']\n", "candidate_gender_cols = ['gender']\n", "\n", "# Read the clinical data file\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)\")\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Preview age 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 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", "print(\"Age columns preview:\")\n", "print(age_preview)\n", "print(\"\\nGender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "5f3310c2", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "2e6c02dc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:05:25.848338Z", "iopub.status.busy": "2025-03-25T07:05:25.848226Z", "iopub.status.idle": "2025-03-25T07:05:25.851493Z", "shell.execute_reply": "2025-03-25T07:05:25.851209Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Age column preview: [44.0, 50.0, 59.0, 56.0, 40.0]\n", "Selected gender column: gender\n", "Gender column preview: ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']\n" ] } ], "source": [ "# Inspecting the age columns\n", "age_columns = {\n", " 'age_at_initial_pathologic_diagnosis': [44.0, 50.0, 59.0, 56.0, 40.0], \n", " 'days_to_birth': [-16179.0, -18341.0, -21617.0, -20516.0, -14806.0], \n", " 'first_diagnosis_age_asth_ecz_hay_fev_mold_dust': [float('nan'), float('nan'), float('nan'), float('nan'), float('nan')], \n", " 'first_diagnosis_age_of_animal_insect_allergy': [float('nan'), float('nan'), float('nan'), float('nan'), float('nan')], \n", " 'first_diagnosis_age_of_food_allergy': [float('nan'), float('nan'), float('nan'), float('nan'), float('nan')]\n", "}\n", "\n", "# Inspecting the gender columns\n", "gender_columns = {\n", " 'gender': ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']\n", "}\n", "\n", "# Select the best age column\n", "# 'age_at_initial_pathologic_diagnosis' has actual age values in years (preferred)\n", "# 'days_to_birth' has negative values representing days since birth, which would need conversion\n", "# The other columns have all NaN values\n", "\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# Select the best gender column\n", "# Only one column is available and it has valid values\n", "gender_col = 'gender'\n", "\n", "# Print the selected columns\n", "print(f\"Selected age column: {age_col}\")\n", "print(f\"Age column preview: {age_columns[age_col]}\")\n", "print(f\"Selected gender column: {gender_col}\")\n", "print(f\"Gender column preview: {gender_columns[gender_col]}\")\n" ] }, { "cell_type": "markdown", "id": "9d4a5e2f", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "a2bf2559", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:05:25.852670Z", "iopub.status.busy": "2025-03-25T07:05:25.852563Z", "iopub.status.idle": "2025-03-25T07:05:39.077258Z", "shell.execute_reply": "2025-03-25T07:05:39.076929Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Canavan_Disease/gene_data/TCGA.csv\n", "Gene expression data shape after normalization: (19848, 530)\n", "Clinical data saved to ../../output/preprocess/Canavan_Disease/clinical_data/TCGA.csv\n", "Clinical data shape: (1148, 3)\n", "Number of samples in clinical data: 1148\n", "Number of samples in genetic data: 530\n", "Number of common samples: 530\n", "Linked data shape: (530, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (530, 19851)\n", "Quartiles for 'Canavan_Disease':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1\n", "Max: 1\n", "The distribution of the feature 'Canavan_Disease' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 32.0\n", " 50% (Median): 41.0\n", " 75%: 53.0\n", "Min: 14.0\n", "Max: 87.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 238 occurrences. This represents 44.91% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Dataset deemed not usable based on validation criteria. Data not saved.\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 }