{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "93dd7a52", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:52:55.703627Z", "iopub.status.busy": "2025-03-25T07:52:55.703201Z", "iopub.status.idle": "2025-03-25T07:52:55.868304Z", "shell.execute_reply": "2025-03-25T07:52:55.867927Z" } }, "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 = \"Lung_Cancer\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Lung_Cancer/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Lung_Cancer/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Lung_Cancer/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Lung_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a61c5c48", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "00769b63", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:52:55.869564Z", "iopub.status.busy": "2025-03-25T07:52:55.869414Z", "iopub.status.idle": "2025-03-25T07:52:58.442395Z", "shell.execute_reply": "2025-03-25T07:52:58.441925Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data columns:\n", "['ABSOLUTE_Ploidy', 'ABSOLUTE_Purity', 'AKT1', 'ALK_translocation', 'BRAF', 'CBL', 'CTNNB1', 'Canonical_mut_in_KRAS_EGFR_ALK', 'Cnncl_mt_n_KRAS_EGFR_ALK_RET_ROS1_BRAF_ERBB2_HRAS_NRAS_AKT1_MAP2', 'EGFR', 'ERBB2', 'ERBB4', 'Estimated_allele_fraction_of_a_clonal_varnt_prsnt_t_1_cpy_pr_cll', 'Expression_Subtype', 'HRAS', 'KRAS', 'MAP2K1', 'MET', 'NRAS', 'PIK3CA', 'PTPN11', 'Pathology', 'Pathology_Updated', 'RET_translocation', 'ROS1_translocation', 'STK11', 'WGS_as_of_20120731_0_no_1_yes', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_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', 'anatomic_neoplasm_subdivision', 'anatomic_neoplasm_subdivision_other', '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', 'disease_code', 'dlco_predictive_percent', 'eastern_cancer_oncology_group', 'egfr_mutation_performed', 'egfr_mutation_result', 'eml4_alk_translocation_method', 'eml4_alk_translocation_performed', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', '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', 'karnofsky_performance_score', 'kras_gene_analysis_performed', 'kras_mutation_found', 'kras_mutation_result', 'location_in_lung_parenchyma', 'longest_dimension', 'lost_follow_up', 'new_neoplasm_event_type', 'new_tumor_event_after_initial_treatment', 'number_pack_years_smoked', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'post_bronchodilator_fev1_fvc_percent', 'post_bronchodilator_fev1_percent', 'pre_bronchodilator_fev1_fvc_percent', 'pre_bronchodilator_fev1_percent', 'primary_therapy_outcome_success', 'progression_determined_by', 'project_code', 'pulmonary_function_test_performed', 'radiation_therapy', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'stopped_smoking_year', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tobacco_smoking_history', 'tobacco_smoking_history_indicator', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', 'year_of_tobacco_smoking_onset', '_GENOMIC_ID_TCGA_LUNG_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LUNG_hMethyl27', '_GENOMIC_ID_TCGA_LUNG_mutation', '_GENOMIC_ID_TCGA_LUNG_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LUNG_hMethyl450', '_GENOMIC_ID_TCGA_LUNG_gistic2thd', '_GENOMIC_ID_TCGA_LUNG_G4502A_07_3', '_GENOMIC_ID_TCGA_LUNG_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LUNG_gistic2', '_GENOMIC_ID_TCGA_LUNG_RPPA_RBN']\n", "\n", "Clinical data shape: (1299, 133)\n", "Genetic data shape: (20530, 1129)\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# Review subdirectories to find the most relevant match for Lung Cancer\n", "all_dirs = os.listdir(tcga_root_dir)\n", "\n", "# Since our trait is \"Lung_Cancer\", we look for directories containing \"Lung\" in the name\n", "lung_related_dirs = [d for d in all_dirs if \"Lung\" in d]\n", "\n", "# Choose the most specific directory for our task\n", "# For Lung Cancer, we have multiple options: TCGA_Lung_Cancer_(LUNG), TCGA_Lung_Adenocarcinoma_(LUAD), \n", "# and TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)\n", "# TCGA_Lung_Cancer_(LUNG) is the most general and appropriate for our trait\n", "selected_dir = \"TCGA_Lung_Cancer_(LUNG)\"\n", "selected_path = os.path.join(tcga_root_dir, selected_dir)\n", "\n", "# Get paths to the clinical and genetic data files\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(selected_path)\n", "\n", "# Load the data files\n", "clinical_data = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n", "genetic_data = pd.read_csv(genetic_file_path, index_col=0, sep='\\t')\n", "\n", "# Print the column names of the clinical data\n", "print(\"Clinical data columns:\")\n", "print(clinical_data.columns.tolist())\n", "\n", "# Also print basic information about both datasets\n", "print(\"\\nClinical data shape:\", clinical_data.shape)\n", "print(\"Genetic data shape:\", genetic_data.shape)\n" ] }, { "cell_type": "markdown", "id": "89c60613", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "1776f812", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:52:58.443850Z", "iopub.status.busy": "2025-03-25T07:52:58.443726Z", "iopub.status.idle": "2025-03-25T07:52:58.458068Z", "shell.execute_reply": "2025-03-25T07:52:58.457725Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Checking contents of ../../input/TCGA\n", "Available folders: ['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", "Using folder: TCGA_Lung_Adenocarcinoma_(LUAD)\n", "Age-related columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [70.0, 67.0, 79.0, 68.0, 66.0], 'days_to_birth': [-25752.0, -24532.0, -29068.0, -24868.0, -24411.0]}\n", "Gender-related columns preview:\n", "{'gender': ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']}\n" ] } ], "source": [ "import os\n", "\n", "# Check the contents of the TCGA root directory to identify the correct folder\n", "print(f\"Checking contents of {tcga_root_dir}\")\n", "tcga_folders = os.listdir(tcga_root_dir)\n", "print(f\"Available folders: {tcga_folders}\")\n", "\n", "# Find a folder that might contain lung cancer data\n", "lung_folder = None\n", "for folder in tcga_folders:\n", " if \"lung\" in folder.lower():\n", " lung_folder = folder\n", " break\n", "\n", "# If no lung-specific folder found, use the first available folder\n", "if not lung_folder and tcga_folders:\n", " lung_folder = tcga_folders[0]\n", " \n", "if lung_folder:\n", " print(f\"Using folder: {lung_folder}\")\n", " cohort_dir = os.path.join(tcga_root_dir, lung_folder)\n", " \n", " # 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 the clinical data\n", " clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n", " clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", " \n", " # Extract and preview age-related columns\n", " age_preview = {}\n", " if candidate_age_cols:\n", " available_age_cols = [col for col in candidate_age_cols if col in clinical_df.columns]\n", " if available_age_cols:\n", " age_df = clinical_df[available_age_cols]\n", " age_preview = preview_df(age_df)\n", " print(\"Age-related columns preview:\")\n", " print(age_preview)\n", " else:\n", " print(\"None of the candidate age columns are available in the dataset\")\n", " \n", " # Extract and preview gender-related columns\n", " gender_preview = {}\n", " if candidate_gender_cols:\n", " available_gender_cols = [col for col in candidate_gender_cols if col in clinical_df.columns]\n", " if available_gender_cols:\n", " gender_df = clinical_df[available_gender_cols]\n", " gender_preview = preview_df(gender_df)\n", " print(\"Gender-related columns preview:\")\n", " print(gender_preview)\n", " else:\n", " print(\"None of the candidate gender columns are available in the dataset\")\n", "else:\n", " print(f\"No folders found in {tcga_root_dir}\")\n" ] }, { "cell_type": "markdown", "id": "897eef4b", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "a8723282", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:52:58.459244Z", "iopub.status.busy": "2025-03-25T07:52:58.459131Z", "iopub.status.idle": "2025-03-25T07:52:58.461580Z", "shell.execute_reply": "2025-03-25T07:52:58.461262Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Age column sample values: ['67.0', '67.0', '72.0', '72.0', '77.0']\n", "Selected gender column: gender\n", "Gender column sample values: ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']\n" ] } ], "source": [ "# Select the appropriate columns for age and gender\n", "age_col = \"age_at_initial_pathologic_diagnosis\"\n", "gender_col = \"gender\"\n", "\n", "# Print information about the chosen columns\n", "print(f\"Selected age column: {age_col}\")\n", "print(f\"Age column sample values: {['67.0', '67.0', '72.0', '72.0', '77.0']}\")\n", "print(f\"Selected gender column: {gender_col}\")\n", "print(f\"Gender column sample values: {['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']}\")\n" ] }, { "cell_type": "markdown", "id": "81ded28f", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "13d660b9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:52:58.462716Z", "iopub.status.busy": "2025-03-25T07:52:58.462606Z", "iopub.status.idle": "2025-03-25T07:54:32.228461Z", "shell.execute_reply": "2025-03-25T07:54:32.227932Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Lung_Cancer/gene_data/TCGA.csv\n", "Gene data shape after normalization: (19848, 1129)\n", "Linked data shape: (1129, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (1129, 19851)\n", "For the feature 'Lung_Cancer', the least common label is '0' with 110 occurrences. This represents 9.74% of the dataset.\n", "The distribution of the feature 'Lung_Cancer' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 60.0\n", " 50% (Median): 67.0\n", " 75%: 73.0\n", "Min: 38.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 455 occurrences. This represents 40.30% 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/Lung_Cancer/TCGA.csv\n", "Clinical data saved to ../../output/preprocess/Lung_Cancer/clinical_data/TCGA.csv\n" ] } ], "source": [ "# Let's first get the correct folder for Lung Cancer data\n", "selected_dir = \"TCGA_Lung_Cancer_(LUNG)\"\n", "selected_path = os.path.join(tcga_root_dir, selected_dir)\n", "\n", "# Reload the clinical and genetic data files to ensure we're using the correct dataset\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(selected_path)\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", "# 1. Extract and standardize clinical features (trait, age, gender)\n", "selected_clinical_df = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=trait, \n", " age_col=age_col, \n", " gender_col=gender_col\n", ")\n", "\n", "# 2. Normalize gene symbols in gene expression data\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 data saved to {out_gene_data_file}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_df.shape}\")\n", "\n", "# 3. Link clinical and genetic data\n", "# Transpose the genetic data to have samples as rows\n", "genetic_df_t = normalized_gene_df.T\n", "# Ensure the indices match between datasets\n", "common_samples = list(set(genetic_df_t.index) & set(selected_clinical_df.index))\n", "genetic_df_filtered = genetic_df_t.loc[common_samples]\n", "clinical_df_filtered = selected_clinical_df.loc[common_samples]\n", "\n", "# Combine the datasets\n", "linked_data = pd.concat([clinical_df_filtered, genetic_df_filtered], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data_cleaned = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Determine if trait and demographic features are biased\n", "is_biased, linked_data_filtered = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", "\n", "# 6. Validate data quality and save cohort information\n", "# First check if gene and trait data are available\n", "is_gene_available = linked_data_filtered.shape[1] > 3 # More columns than just trait, age, gender\n", "is_trait_available = trait in linked_data_filtered.columns\n", "\n", "# Second validation for saving metadata\n", "note = f\"Dataset contains {linked_data_filtered.shape[0]} samples and {linked_data_filtered.shape[1] - 3} genes after preprocessing.\"\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data_filtered,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_filtered.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " \n", " # Also save the clinical data separately\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_cols = [col for col in linked_data_filtered.columns if col in [trait, 'Age', 'Gender']]\n", " linked_data_filtered[clinical_cols].to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"Dataset not usable for analysis. 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 }