{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "bd718cab", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:59.663309Z", "iopub.status.busy": "2025-03-25T07:39:59.663126Z", "iopub.status.idle": "2025-03-25T07:39:59.827421Z", "shell.execute_reply": "2025-03-25T07:39:59.827090Z" } }, "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 = \"lower_grade_glioma_and_glioblastoma\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/lower_grade_glioma_and_glioblastoma/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/lower_grade_glioma_and_glioblastoma/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/lower_grade_glioma_and_glioblastoma/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/lower_grade_glioma_and_glioblastoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "67908d58", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "4a802263", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:39:59.828651Z", "iopub.status.busy": "2025-03-25T07:39:59.828513Z", "iopub.status.idle": "2025-03-25T07:40:01.329785Z", "shell.execute_reply": "2025-03-25T07:40:01.329449Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Available TCGA directories: ['TCGA_Liver_Cancer_(LIHC)', 'TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Mesothelioma_(MESO)', 'TCGA_Ocular_melanomas_(UVM)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Thymoma_(THYM)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Uterine_Carcinosarcoma_(UCS)', '.DS_Store', 'CrawlData.ipynb', 'TCGA_Acute_Myeloid_Leukemia_(LAML)', 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)']\n", "Potential relevant directories for lower_grade_glioma_and_glioblastoma: ['TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)']\n", "Selected directory for lower_grade_glioma_and_glioblastoma: TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)\n", "Clinical data file: ../../input/TCGA/TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)/TCGA.GBMLGG.sampleMap_GBMLGG_clinicalMatrix\n", "Genetic data file: ../../input/TCGA/TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)/TCGA.GBMLGG.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_mutation_PANCAN', '_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_additional_surgery_procedure', '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_pathologic_diagnosis_method', '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_neoplasm_event_type', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'oct_embedded', 'other_dx', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'preoperative_antiseizure_meds', 'preoperative_corticosteroids', 'primary_therapy_outcome_success', 'prior_glioma', '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_GBMLGG_exp_HiSeqV2', '_GENOMIC_ID_TCGA_GBMLGG_PDMarrayCNV', '_GENOMIC_ID_TCGA_GBMLGG_mutation', '_GENOMIC_ID_TCGA_GBMLGG_hMethyl450', '_GENOMIC_ID_TCGA_GBMLGG_PDMarray', '_GENOMIC_ID_TCGA_GBMLGG_gistic2', '_GENOMIC_ID_TCGA_GBMLGG_PDMRNAseq', '_GENOMIC_ID_TCGA_GBMLGG_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_GBMLGG_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_GBMLGG_gistic2thd', '_GENOMIC_ID_TCGA_GBMLGG_exp_HiSeqV2_exon']\n" ] } ], "source": [ "# Step 1: Review subdirectories to find one related to lower_grade_glioma_and_glioblastoma\n", "import os\n", "\n", "# List all directories in TCGA root directory\n", "tcga_dirs = os.listdir(tcga_root_dir)\n", "print(f\"Available TCGA directories: {tcga_dirs}\")\n", "\n", "# Look for directories related to lower_grade_glioma_and_glioblastoma\n", "relevant_dirs = []\n", "for dir_name in tcga_dirs:\n", " dir_lower = dir_name.lower()\n", " if trait.lower().replace(\"_\", \" \") in dir_lower.replace(\"_\", \" \"):\n", " relevant_dirs.append(dir_name)\n", " elif \"gbmlgg\" in dir_lower: # Specific acronym for lower grade glioma and glioblastoma\n", " relevant_dirs.append(dir_name)\n", " elif (\"glioma\" in dir_lower and \"glioblastoma\" in dir_lower):\n", " relevant_dirs.append(dir_name)\n", "\n", "print(f\"Potential relevant directories for {trait}: {relevant_dirs}\")\n", "\n", "if not relevant_dirs:\n", " print(f\"No directory specifically relevant to the trait: {trait}\")\n", " \n", " validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=False,\n", " is_trait_available=False\n", " )\n", " print(f\"Task marked as completed. {trait} is not directly represented in the TCGA dataset.\")\n", "else:\n", " # If we found a relevant directory, proceed with loading the data\n", " selected_dir = relevant_dirs[0]\n", " print(f\"Selected directory for {trait}: {selected_dir}\")\n", " \n", " # Get the full path to the directory\n", " cohort_dir = os.path.join(tcga_root_dir, selected_dir)\n", " \n", " # Step 2: Find clinical and genetic data files\n", " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", " \n", " print(f\"Clinical data file: {clinical_file_path}\")\n", " print(f\"Genetic data file: {genetic_file_path}\")\n", " \n", " # Step 3: Load the data files\n", " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n", " genetic_df = pd.read_csv(genetic_file_path, index_col=0, sep='\\t')\n", " \n", " # Step 4: Print column names of clinical data\n", " print(\"\\nClinical data columns:\")\n", " print(clinical_df.columns.tolist())\n", " \n", " # Check if both datasets are available\n", " is_gene_available = not genetic_df.empty\n", " is_trait_available = not clinical_df.empty\n", " \n", " # Initial validation\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" ] }, { "cell_type": "markdown", "id": "3f905773", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "483b8310", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:40:01.331596Z", "iopub.status.busy": "2025-03-25T07:40:01.331489Z", "iopub.status.idle": "2025-03-25T07:40:01.345470Z", "shell.execute_reply": "2025-03-25T07:40:01.345180Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age column previews:\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 column previews:\n", "{'gender': ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Step 1: Identify potential age and gender columns\n", "candidate_age_cols = [\n", " 'age_at_initial_pathologic_diagnosis', \n", " 'days_to_birth',\n", " 'first_diagnosis_age_asth_ecz_hay_fev_mold_dust',\n", " 'first_diagnosis_age_of_animal_insect_allergy',\n", " 'first_diagnosis_age_of_food_allergy'\n", "]\n", "\n", "candidate_gender_cols = ['gender']\n", "\n", "# Step 2: Extract and preview these columns from the clinical data\n", "# First, get the file paths\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)\")\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Load the clinical data\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Extract and 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", "print(\"Age column previews:\")\n", "print(age_preview)\n", "\n", "# Extract and 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(\"\\nGender column previews:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "93f5857d", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "64f03a42", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:40:01.347047Z", "iopub.status.busy": "2025-03-25T07:40:01.346941Z", "iopub.status.idle": "2025-03-25T07:40:01.350088Z", "shell.execute_reply": "2025-03-25T07:40:01.349815Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# Examine the age column previews\n", "age_col = None\n", "gender_col = None\n", "\n", "# Select age column\n", "age_cols_preview = {\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': [None, None, None, None, None], \n", " 'first_diagnosis_age_of_animal_insect_allergy': [None, None, None, None, None], \n", " 'first_diagnosis_age_of_food_allergy': [None, None, None, None, None]\n", "}\n", "\n", "# Select gender column\n", "gender_cols_preview = {\n", " 'gender': ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']\n", "}\n", "\n", "# For age, we want a column with actual age values, not missing values or negative numbers (days)\n", "# 'age_at_initial_pathologic_diagnosis' contains valid age values\n", "if 'age_at_initial_pathologic_diagnosis' in age_cols_preview and not all(val is None for val in age_cols_preview['age_at_initial_pathologic_diagnosis']):\n", " age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# For gender, we want a column with valid gender values (male/female)\n", "if 'gender' in gender_cols_preview and not all(val is None for val in gender_cols_preview['gender']):\n", " gender_col = 'gender'\n", "\n", "# Print the chosen columns\n", "print(f\"Selected age column: {age_col}\")\n", "print(f\"Selected gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "3ddbeb6e", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "10fa4ffd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:40:01.351367Z", "iopub.status.busy": "2025-03-25T07:40:01.351269Z", "iopub.status.idle": "2025-03-25T07:41:01.592012Z", "shell.execute_reply": "2025-03-25T07:41:01.591341Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Saved clinical data with 1148 samples\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 19848 genes remaining\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene expression data\n", "Linked data shape: (702, 19851) (samples x features)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (702, 19850)\n", "For the feature 'lower_grade_glioma_and_glioblastoma', the least common label is '0' with 5 occurrences. This represents 0.71% of the dataset.\n", "The distribution of the feature 'lower_grade_glioma_and_glioblastoma' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 34.0\n", " 50% (Median): 46.0\n", " 75%: 59.0\n", "Min: 14.0\n", "Max: 89.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved usable linked data to ../../output/preprocess/lower_grade_glioma_and_glioblastoma/TCGA.csv\n" ] } ], "source": [ "# Step 1: Extract and standardize clinical features\n", "# Use the Lower Grade Glioma and Glioblastoma directory identified in Step 1\n", "selected_dir = \"TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)\" # Use the correct directory from Step 1\n", "cohort_dir = os.path.join(tcga_root_dir, selected_dir)\n", "\n", "# Get the file paths for clinical and genetic data\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Load the data\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", "# Extract standardized clinical features using the provided trait variable\n", "clinical_features = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=trait, # Using the provided trait variable\n", " age_col=age_col, \n", " gender_col=gender_col\n", ")\n", "\n", "# Convert gender values from text (FEMALE/MALE) to numeric (0/1)\n", "if 'Gender' in clinical_features.columns:\n", " clinical_features['Gender'] = clinical_features['Gender'].apply(tcga_convert_gender)\n", "\n", "# Save the clinical data to out_clinical_data_file\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\"Saved clinical data with {len(clinical_features)} samples\")\n", "\n", "# Step 2: Normalize gene symbols in gene expression data\n", "# Transpose to get genes as rows\n", "gene_df = genetic_df\n", "\n", "# Normalize gene symbols using NCBI Gene database synonyms\n", "normalized_gene_df = normalize_gene_symbols_in_index(gene_df)\n", "print(f\"After normalization: {len(normalized_gene_df)} genes remaining\")\n", "\n", "# Save the normalized gene expression 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\"Saved normalized gene expression data\")\n", "\n", "# Step 3: Link clinical and genetic data\n", "# Merge clinical features with genetic expression data\n", "linked_data = clinical_features.join(normalized_gene_df.T, how='inner')\n", "print(f\"Linked data shape: {linked_data.shape} (samples x features)\")\n", "\n", "# Step 4: Handle missing values\n", "cleaned_data = handle_missing_values(linked_data, trait_col=trait)\n", "print(f\"After handling missing values, data shape: {cleaned_data.shape}\")\n", "\n", "# Step 5: Determine if trait or demographics are severely biased\n", "trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait=trait)\n", "\n", "# Step 6: Validate data quality and save cohort information\n", "note = \"The dataset contains gene expression data along with clinical information for lower grade glioma and glioblastoma patients from TCGA.\"\n", "\n", "# Validate the data and determine if it's usable\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=len(normalized_gene_df) > 0,\n", " is_trait_available=True,\n", " is_biased=trait_biased, # Use the actual bias determination\n", " df=cleaned_data,\n", " note=note\n", ")\n", "\n", "# Step 7: Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Saved usable linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset was determined to be unusable and was 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 }