{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "edc1580d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:54:46.487732Z", "iopub.status.busy": "2025-03-25T06:54:46.487626Z", "iopub.status.idle": "2025-03-25T06:54:46.652967Z", "shell.execute_reply": "2025-03-25T06:54:46.652521Z" } }, "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 = \"Bile_Duct_Cancer\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Bile_Duct_Cancer/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Bile_Duct_Cancer/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Bile_Duct_Cancer/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Bile_Duct_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "0982780f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "4cefa8b4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:54:46.654529Z", "iopub.status.busy": "2025-03-25T06:54:46.654266Z", "iopub.status.idle": "2025-03-25T06:54:46.819017Z", "shell.execute_reply": "2025-03-25T06:54:46.818484Z" } }, "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", "Found matching directory for Bile_Duct_Cancer: TCGA_Bile_Duct_Cancer_(CHOL)\n", "\n", "Selected directory: TCGA_Bile_Duct_Cancer_(CHOL)\n", "Clinical data file: TCGA.CHOL.sampleMap_CHOL_clinicalMatrix\n", "Genetic data file: TCGA.CHOL.sampleMap_HiSeqV2_PANCAN.gz\n", "\n", "Clinical data columns:\n", "['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'albumin_result_lower_limit', 'albumin_result_specified_value', 'albumin_result_upper_limit', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'bilirubin_lower_limit', 'bilirubin_upper_limit', 'ca_19_9_level', 'ca_19_9_level_lower', 'ca_19_9_level_upper', 'cancer_first_degree_relative', 'child_pugh_classification_grade', 'cholangitis_tissue_evidence', 'creatinine_lower_level', 'creatinine_upper_limit', 'creatinine_value_in_mg_dl', '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', 'eastern_cancer_oncology_group', 'family_cancer_type_txt', 'family_member_relationship_type', 'fetoprotein_outcome_lower_limit', 'fetoprotein_outcome_upper_limit', 'fetoprotein_outcome_value', 'fibrosis_ishak_score', 'form_completion_date', 'gender', 'height', 'hist_hepato_carc_fact', 'hist_hepato_carcinoma_risk', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'inter_norm_ratio_lower_limit', 'intern_norm_ratio_upper_limit', 'is_ffpe', 'lost_follow_up', 'neoplasm_histologic_grade', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_tumor_event_ablation_embo_tx', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'new_tumor_event_liver_transplant', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'perineural_invasion_present', 'person_neoplasm_cancer_status', 'platelet_result_count', 'platelet_result_lower_limit', 'platelet_result_upper_limit', 'post_op_ablation_embolization_tx', 'postoperative_rx_tx', 'prothrombin_time_result_value', 'radiation_therapy', 'relative_family_cancer_history', 'residual_tumor', 'sample_type', 'sample_type_id', 'specimen_collection_method_name', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_bilirubin_upper_limit', 'tumor_tissue_site', 'vascular_tumor_cell_type', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_CHOL_mutation_broad_gene', '_GENOMIC_ID_TCGA_CHOL_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_CHOL_hMethyl450', '_GENOMIC_ID_TCGA_CHOL_exp_HiSeqV2', '_GENOMIC_ID_TCGA_CHOL_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_CHOL_mutation_bcm_gene', '_GENOMIC_ID_TCGA_CHOL_miRNA_HiSeq', '_GENOMIC_ID_TCGA_CHOL_gistic2thd', '_GENOMIC_ID_TCGA_CHOL_gistic2', '_GENOMIC_ID_TCGA_CHOL_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_CHOL_exp_HiSeqV2_exon', '_GENOMIC_ID_data/public/TCGA/CHOL/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_CHOL_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_CHOL_PDMRNAseq', '_GENOMIC_ID_TCGA_CHOL_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_CHOL_RPPA']\n" ] } ], "source": [ "import os\n", "\n", "# List all subdirectories in tcga_root_dir\n", "subdirs = os.listdir(tcga_root_dir)\n", "print(f\"Available TCGA directories: {subdirs}\")\n", "\n", "# Look for the directory matching Bile Duct Cancer\n", "bile_duct_dir = None\n", "for dir_name in subdirs:\n", " if 'Bile_Duct_Cancer' in dir_name or 'CHOL' in dir_name:\n", " bile_duct_dir = dir_name\n", " break\n", "\n", "if bile_duct_dir:\n", " print(f\"Found matching directory for {trait}: {bile_duct_dir}\")\n", " cohort_dir = os.path.join(tcga_root_dir, bile_duct_dir)\n", " \n", " # Get paths to clinical and genetic files\n", " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", " \n", " # Load clinical and genetic data\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", " print(f\"\\nSelected directory: {bile_duct_dir}\")\n", " print(f\"Clinical data file: {os.path.basename(clinical_file_path)}\")\n", " print(f\"Genetic data file: {os.path.basename(genetic_file_path)}\")\n", " \n", " # Print column names of clinical data\n", " print(\"\\nClinical data columns:\")\n", " print(clinical_df.columns.tolist())\n", " \n", " # Check if gene expression and trait data are available\n", " is_gene_available = not genetic_df.empty\n", " is_trait_available = not clinical_df.empty\n", " \n", " # Only validate, don't finalize\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", "else:\n", " print(f\"No suitable directory found for {trait}.\")\n", " \n", " # Mark this cohort as not usable for Bile Duct Cancer research\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" ] }, { "cell_type": "markdown", "id": "bfaabed2", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "560e28cd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:54:46.820503Z", "iopub.status.busy": "2025-03-25T06:54:46.820388Z", "iopub.status.idle": "2025-03-25T06:54:46.827032Z", "shell.execute_reply": "2025-03-25T06:54:46.826639Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [72, 50, 70, 72, 60], 'days_to_birth': [-26349, -18303, -25819, -26493, -21943]}\n", "Gender columns preview:\n", "{'gender': ['MALE', 'FEMALE', 'FEMALE', 'FEMALE', 'MALE']}\n" ] } ], "source": [ "# Identify candidate columns for age and gender\n", "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n", "candidate_gender_cols = ['gender']\n", "\n", "# Load clinical data to preview these columns\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Bile_Duct_Cancer_(CHOL)\")\n", "clinical_file, _ = tcga_get_relevant_filepaths(cohort_dir)\n", "clinical_df = pd.read_csv(clinical_file, sep='\\t', index_col=0)\n", "\n", "# Preview age columns\n", "if candidate_age_cols:\n", " age_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_age_cols if col in clinical_df.columns}\n", " print(\"Age columns preview:\")\n", " print(age_preview)\n", "\n", "# Preview gender columns\n", "if candidate_gender_cols:\n", " gender_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_gender_cols if col in clinical_df.columns}\n", " print(\"Gender columns preview:\")\n", " print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "8831acf3", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "574b116b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:54:46.828411Z", "iopub.status.busy": "2025-03-25T06:54:46.828304Z", "iopub.status.idle": "2025-03-25T06:54:46.831260Z", "shell.execute_reply": "2025-03-25T06:54:46.830856Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# Examining the age columns\n", "age_columns = {'age_at_initial_pathologic_diagnosis': [72, 50, 70, 72, 60], \n", " 'days_to_birth': [-26349, -18303, -25819, -26493, -21943]}\n", "\n", "# Examining the gender columns\n", "gender_columns = {'gender': ['MALE', 'FEMALE', 'FEMALE', 'FEMALE', 'MALE']}\n", "\n", "# Select the best columns for age and gender\n", "# For age, we prefer 'age_at_initial_pathologic_diagnosis' as it provides direct age values\n", "# 'days_to_birth' provides negative values representing days from birth (would need conversion)\n", "age_col = 'age_at_initial_pathologic_diagnosis' if 'age_at_initial_pathologic_diagnosis' in age_columns else None\n", "\n", "# For gender, 'gender' is the only available column and appears to have valid values\n", "gender_col = 'gender' if 'gender' in gender_columns else None\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": "696fc148", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "4288b407", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:54:46.832604Z", "iopub.status.busy": "2025-03-25T06:54:46.832497Z", "iopub.status.idle": "2025-03-25T06:54:56.652776Z", "shell.execute_reply": "2025-03-25T06:54:56.651940Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Extracting clinical features...\n", "Clinical features shape: (45, 3)\n", "Preview of clinical features:\n", " Bile_Duct_Cancer Age Gender\n", "sampleID \n", "TCGA-3X-AAV9-01 1 72 1\n", "TCGA-3X-AAVA-01 1 50 0\n", "TCGA-3X-AAVB-01 1 70 0\n", "TCGA-3X-AAVC-01 1 72 0\n", "TCGA-3X-AAVE-01 1 60 1\n", "Clinical data saved to ../../output/preprocess/Bile_Duct_Cancer/clinical_data/TCGA.csv\n", "\n", "Normalizing gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original gene expression data shape: (20530, 45)\n", "Normalized gene expression data shape: (19848, 45)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Bile_Duct_Cancer/gene_data/TCGA.csv\n", "\n", "Linking clinical and genetic data...\n", "Number of common samples: 45\n", "Linked data shape: (45, 19851)\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (45, 19851)\n", "\n", "Checking for biased features...\n", "For the feature 'Bile_Duct_Cancer', the least common label is '0' with 9 occurrences. This represents 20.00% of the dataset.\n", "The distribution of the feature 'Bile_Duct_Cancer' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 58.0\n", " 50% (Median): 68.0\n", " 75%: 73.0\n", "Min: 29\n", "Max: 82\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1' with 22 occurrences. This represents 48.89% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "\n", "Validating final data quality...\n", "\n", "Data is usable. Saving linked data to ../../output/preprocess/Bile_Duct_Cancer/TCGA.csv...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Bile_Duct_Cancer/TCGA.csv\n" ] } ], "source": [ "# Step: Feature Engineering and Validation\n", "\n", "# 1. Extract and standardize clinical features\n", "print(\"\\nExtracting clinical features...\")\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", "print(f\"Clinical features shape: {clinical_features.shape}\")\n", "print(f\"Preview of clinical features:\\n{clinical_features.head()}\")\n", "\n", "# Save 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", "\n", "# 2. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene expression data...\")\n", "genetic_df_normalized = normalize_gene_symbols_in_index(genetic_df)\n", "print(f\"Original gene expression data shape: {genetic_df.shape}\")\n", "print(f\"Normalized gene expression data shape: {genetic_df_normalized.shape}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "genetic_df_normalized.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "\n", "# 3. Link the clinical and genetic data on sample IDs\n", "print(\"\\nLinking clinical and genetic data...\")\n", "# Transpose genetic data to have samples as rows and genes as columns\n", "genetic_df_for_linking = genetic_df_normalized.T\n", "\n", "# Ensure sample IDs in clinical features match those in genetic data\n", "common_samples = clinical_features.index.intersection(genetic_df_for_linking.index)\n", "print(f\"Number of common samples: {len(common_samples)}\")\n", "\n", "# Filter both dataframes to keep only common samples\n", "clinical_features_common = clinical_features.loc[common_samples]\n", "genetic_df_common = genetic_df_for_linking.loc[common_samples]\n", "\n", "# Combine clinical and genetic data\n", "linked_data = pd.concat([clinical_features_common, genetic_df_common], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values systematically\n", "print(\"\\nHandling missing values...\")\n", "linked_data_clean = handle_missing_values(linked_data, trait_col=trait)\n", "print(f\"Data shape after handling missing values: {linked_data_clean.shape}\")\n", "\n", "# 5. Determine if trait or demographic features are biased\n", "print(\"\\nChecking for biased features...\")\n", "is_trait_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n", "\n", "# 6. Validate data quality and save cohort information\n", "print(\"\\nValidating final data quality...\")\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=genetic_df_normalized.shape[0] > 0,\n", " is_trait_available=clinical_features.shape[0] > 0,\n", " is_biased=is_trait_biased,\n", " df=linked_data_clean,\n", " note=\"Pancreatic cancer dataset used as proxy for Type 2 Diabetes due to pancreatic involvement in diabetes.\"\n", ")\n", "\n", "# 7. Save the linked data if usable\n", "if is_usable:\n", " print(f\"\\nData is usable. Saving linked data to {out_data_file}...\")\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_clean.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"\\nData is not usable. Linked data will not be 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 }