{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "e831f067", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:22.626862Z", "iopub.status.busy": "2025-03-25T07:36:22.626597Z", "iopub.status.idle": "2025-03-25T07:36:22.809471Z", "shell.execute_reply": "2025-03-25T07:36:22.809137Z" } }, "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 = \"Longevity\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Longevity/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Longevity/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Longevity/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Longevity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d8a86f74", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "cd52ef19", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:22.810911Z", "iopub.status.busy": "2025-03-25T07:36:22.810771Z", "iopub.status.idle": "2025-03-25T07:36:25.500654Z", "shell.execute_reply": "2025-03-25T07:36:25.500306Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Available TCGA subdirectories: ['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", "Searching for datasets suitable for longevity analysis...\n", "Selected directory: TCGA_Breast_Cancer_(BRCA) for longevity analysis\n", "Clinical file: TCGA.BRCA.sampleMap_BRCA_clinicalMatrix\n", "Genetic file: TCGA.BRCA.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['AJCC_Stage_nature2012', 'Age_at_Initial_Pathologic_Diagnosis_nature2012', 'CN_Clusters_nature2012', 'Converted_Stage_nature2012', 'Days_to_Date_of_Last_Contact_nature2012', 'Days_to_date_of_Death_nature2012', 'ER_Status_nature2012', 'Gender_nature2012', 'HER2_Final_Status_nature2012', 'Integrated_Clusters_no_exp__nature2012', 'Integrated_Clusters_unsup_exp__nature2012', 'Integrated_Clusters_with_PAM50__nature2012', 'Metastasis_Coded_nature2012', 'Metastasis_nature2012', 'Node_Coded_nature2012', 'Node_nature2012', 'OS_Time_nature2012', 'OS_event_nature2012', 'PAM50Call_RNAseq', 'PAM50_mRNA_nature2012', 'PR_Status_nature2012', 'RPPA_Clusters_nature2012', 'SigClust_Intrinsic_mRNA_nature2012', 'SigClust_Unsupervised_mRNA_nature2012', 'Survival_Data_Form_nature2012', 'Tumor_T1_Coded_nature2012', 'Tumor_nature2012', 'Vital_Status_nature2012', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_BRCA', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_BRCA', '_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', 'axillary_lymph_node_stage_method_type', 'axillary_lymph_node_stage_other_method_descriptive_text', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'breast_cancer_surgery_margin_status', 'breast_carcinoma_estrogen_receptor_status', 'breast_carcinoma_immunohistochemistry_er_pos_finding_scale', 'breast_carcinoma_immunohistochemistry_pos_cell_score', 'breast_carcinoma_immunohistochemistry_prgstrn_rcptr_ps_fndng_scl', 'breast_carcinoma_primary_surgical_procedure_name', 'breast_carcinoma_progesterone_receptor_status', 'breast_carcinoma_surgical_procedure_name', 'breast_neoplasm_other_surgical_procedure_descriptive_text', 'cytokeratin_immunohistochemistry_staining_method_mcrmtstss_ndctr', '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_last_known_alive', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'disease_code', 'distant_metastasis_present_ind2', 'er_detection_method_text', 'er_level_cell_percentage_category', 'fluorescence_in_st_hybrdztn_dgnstc_prcdr_chrmsm_17_sgnl_rslt_rng', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'her2_and_centromere_17_positive_finding_other_measuremnt_scl_txt', 'her2_erbb_method_calculation_method_text', 'her2_erbb_pos_finding_cell_percent_category', 'her2_erbb_pos_finding_fluorescence_n_st_hybrdztn_clcltn_mthd_txt', 'her2_immunohistochemistry_level_result', 'her2_neu_and_centromere_17_copy_number_analysis_npt_ttl_nmbr_cnt', 'her2_neu_breast_carcinoma_copy_analysis_input_total_number', 'her2_neu_chromosone_17_signal_ratio_value', 'her2_neu_metastatic_breast_carcinoma_copy_analysis_inpt_ttl_nmbr', 'histological_type', 'histological_type_other', 'history_of_neoadjuvant_treatment', 'hr2_n_nd_cntrmr_17_cpy_nmbr_mtsttc_brst_crcnm_nlyss_npt_ttl_nmbr', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'immunohistochemistry_positive_cell_score', 'informed_consent_verified', 'init_pathology_dx_method_other', 'initial_pathologic_diagnosis_method', 'initial_weight', 'is_ffpe', 'lab_proc_her2_neu_immunohistochemistry_receptor_status', 'lab_procedure_her2_neu_in_situ_hybrid_outcome_type', 'lost_follow_up', 'lymph_node_examined_count', 'margin_status', 'menopause_status', 'metastatic_breast_carcinm_ps_fndng_prgstrn_rcptr_thr_msr_scl_txt', 'metastatic_breast_carcinom_lb_prc_hr2_n_mmnhstchmstry_rcptr_stts', 'metastatic_breast_carcinoma_erbb2_immunohistochemistry_levl_rslt', 'metastatic_breast_carcinoma_estrogen_receptor_detection_mthd_txt', 'metastatic_breast_carcinoma_estrogen_receptor_status', 'metastatic_breast_carcinoma_estrogen_receptr_lvl_cll_prcnt_ctgry', 'metastatic_breast_carcinoma_her2_erbb_method_calculatin_mthd_txt', 'metastatic_breast_carcinoma_her2_erbb_pos_findng_cll_prcnt_ctgry', 'metastatic_breast_carcinoma_her2_neu_chromosone_17_signal_rat_vl', 'metastatic_breast_carcinoma_immunhstchmstry_r_pstv_fndng_scl_typ', 'metastatic_breast_carcinoma_immunohistochemistry_er_pos_cell_scr', 'metastatic_breast_carcinoma_immunohistochemistry_pr_pos_cell_scr', 'metastatic_breast_carcinoma_lab_proc_hr2_n_n_st_hybrdztn_tcm_typ', 'metastatic_breast_carcinoma_pos_finding_hr2_rbb2_thr_msr_scl_txt', 'metastatic_breast_carcinoma_progestern_rcptr_lvl_cll_prcnt_ctgry', 'metastatic_breast_carcinoma_progesterone_receptor_dtctn_mthd_txt', 'metastatic_breast_carcinoma_progesterone_receptor_status', 'metastatic_site_at_diagnosis', 'metastatic_site_at_diagnosis_other', 'methylation_Clusters_nature2012', 'miRNA_Clusters_nature2012', 'mtsttc_brst_crcnm_flrscnc_n_st_hybrdztn_dgnstc_prc_cntrmr_17_sgn', 'mtsttc_brst_crcnm_hr2_rbb_ps_fndng_flrscnc_n_st_hybrdztn_clcltn', 'mtsttc_brst_crcnm_mmnhstchmstry_prgstrn_rcptr_pstv_fndng_scl_typ', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'number_of_lymphnodes_positive_by_he', 'number_of_lymphnodes_positive_by_ihc', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'person_neoplasm_cancer_status', 'pgr_detection_method_text', 'pos_finding_her2_erbb2_other_measurement_scale_text', 'pos_finding_metastatic_brst_crcnm_strgn_rcptr_thr_msrmnt_scl_txt', 'pos_finding_progesterone_receptor_other_measurement_scale_text', 'positive_finding_estrogen_receptor_other_measurement_scale_text', 'postoperative_rx_tx', 'primary_lymph_node_presentation_assessment', 'progesterone_receptor_level_cell_percent_category', 'project_code', 'radiation_therapy', 'sample_type', 'sample_type_id', 'surgical_procedure_purpose_other_text', '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_BRCA_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_BRCA_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_BRCA_RPPA_RBN', '_GENOMIC_ID_TCGA_BRCA_mutation', '_GENOMIC_ID_TCGA_BRCA_PDMRNAseq', '_GENOMIC_ID_TCGA_BRCA_hMethyl450', '_GENOMIC_ID_TCGA_BRCA_RPPA', '_GENOMIC_ID_TCGA_BRCA_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_BRCA_mutation_curated_wustl_gene', '_GENOMIC_ID_TCGA_BRCA_hMethyl27', '_GENOMIC_ID_TCGA_BRCA_PDMarrayCNV', '_GENOMIC_ID_TCGA_BRCA_miRNA_HiSeq', '_GENOMIC_ID_TCGA_BRCA_mutation_wustl_gene', '_GENOMIC_ID_TCGA_BRCA_miRNA_GA', '_GENOMIC_ID_TCGA_BRCA_exp_HiSeqV2_percentile', '_GENOMIC_ID_data/public/TCGA/BRCA/miRNA_GA_gene', '_GENOMIC_ID_TCGA_BRCA_gistic2thd', '_GENOMIC_ID_data/public/TCGA/BRCA/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_BRCA_G4502A_07_3', '_GENOMIC_ID_TCGA_BRCA_exp_HiSeqV2', '_GENOMIC_ID_TCGA_BRCA_gistic2', '_GENOMIC_ID_TCGA_BRCA_PDMarray']\n", "\n", "Clinical data shape: (1247, 193)\n", "Genetic data shape: (20530, 1218)\n", "\n", "Survival-related columns found:\n", "['Days_to_Date_of_Last_Contact_nature2012', 'Days_to_date_of_Death_nature2012', 'Survival_Data_Form_nature2012', 'Vital_Status_nature2012', 'bcr_followup_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_last_known_alive', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'followup_case_report_form_submission_reason', 'lost_follow_up', 'vital_status']\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# 1. List all subdirectories in the TCGA root directory\n", "subdirectories = os.listdir(tcga_root_dir)\n", "print(f\"Available TCGA subdirectories: {subdirectories}\")\n", "\n", "# The target trait is Longevity\n", "target_trait = trait.lower() # \"longevity\"\n", "\n", "# For longevity, we should look for datasets with good survival/aging data\n", "# rather than matching the term directly to a cancer type\n", "print(f\"Searching for datasets suitable for {target_trait} analysis...\")\n", "\n", "# Since longevity relates to survival time and patient outcomes, \n", "# we'll select a cancer type with typically good survival data coverage\n", "# Choosing TCGA_Breast_Cancer_(BRCA) as it typically has a large cohort with varied survival outcomes\n", "selected_dir = \"TCGA_Breast_Cancer_(BRCA)\"\n", "\n", "# Verify the directory exists\n", "if selected_dir in subdirectories:\n", " print(f\"Selected directory: {selected_dir} for longevity analysis\")\n", " \n", " # 2. Get the clinical and genetic data file paths\n", " cohort_dir = os.path.join(tcga_root_dir, selected_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 the clinical data contains survival-related columns\n", " survival_columns = [col for col in clinical_df.columns if any(term in col.lower() for term in \n", " ['survival', 'death', 'follow', 'vital', 'days_to'])]\n", " print(\"\\nSurvival-related columns found:\")\n", " print(survival_columns)\n", " \n", " # Check if we have both gene and survival data\n", " is_gene_available = genetic_df.shape[0] > 0\n", " is_trait_available = clinical_df.shape[0] > 0 and len(survival_columns) > 0\n", " \n", "else:\n", " print(f\"Directory {selected_dir} not found. Checking for alternative datasets...\")\n", " # Alternative approach: search for a dataset with good survival information\n", " is_gene_available = False\n", " is_trait_available = False\n", " \n", " for subdir in subdirectories:\n", " if os.path.isdir(os.path.join(tcga_root_dir, subdir)) and not subdir.startswith('.'):\n", " try:\n", " cohort_dir = os.path.join(tcga_root_dir, subdir)\n", " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", " \n", " # Quick check of clinical 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", " # Look for survival columns\n", " survival_columns = [col for col in clinical_df.columns if any(term in col.lower() for term in \n", " ['survival', 'death', 'follow', 'vital', 'days_to'])]\n", " \n", " if len(survival_columns) > 0 and clinical_df.shape[0] > 100 and genetic_df.shape[0] > 0:\n", " print(f\"Selected alternative directory: {subdir}\")\n", " print(f\"Clinical file: {os.path.basename(clinical_file_path)}\")\n", " print(f\"Genetic file: {os.path.basename(genetic_file_path)}\")\n", " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n", " print(f\"Genetic data shape: {genetic_df.shape}\")\n", " print(\"\\nSurvival-related columns found:\")\n", " print(survival_columns)\n", " \n", " is_gene_available = True\n", " is_trait_available = True\n", " break\n", " \n", " except Exception as e:\n", " print(f\"Error processing {subdir}: {e}\")\n", " continue\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 is_gene_available or not is_trait_available:\n", " print(\"Skipping this trait as no suitable survival data was found in TCGA.\")\n" ] }, { "cell_type": "markdown", "id": "bb1da3f7", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "546f8403", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:25.501866Z", "iopub.status.busy": "2025-03-25T07:36:25.501753Z", "iopub.status.idle": "2025-03-25T07:36:25.523465Z", "shell.execute_reply": "2025-03-25T07:36:25.523149Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'Age_at_Initial_Pathologic_Diagnosis_nature2012': [nan, nan, nan, nan, nan], 'age_at_initial_pathologic_diagnosis': [55.0, 50.0, 62.0, 52.0, 50.0], 'days_to_birth': [-20211.0, -18538.0, -22848.0, -19074.0, -18371.0]}\n", "\n", "Gender columns preview:\n", "{'Gender_nature2012': [nan, nan, nan, nan, nan], 'gender': ['FEMALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Find candidate age columns\n", "candidate_age_cols = [\n", " \"Age_at_Initial_Pathologic_Diagnosis_nature2012\",\n", " \"age_at_initial_pathologic_diagnosis\",\n", " \"days_to_birth\" # Can be used to calculate age\n", "]\n", "\n", "# Find candidate gender columns\n", "candidate_gender_cols = [\n", " \"Gender_nature2012\",\n", " \"gender\"\n", "]\n", "\n", "# Preview the selected columns\n", "# First, get the clinical file path\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Breast_Cancer_(BRCA)\")\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 candidate 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", "# Extract candidate 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", "# Display previews\n", "print(\"Age columns preview:\")\n", "print(age_preview)\n", "print(\"\\nGender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "221adb17", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "8f978524", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:25.524705Z", "iopub.status.busy": "2025-03-25T07:36:25.524593Z", "iopub.status.idle": "2025-03-25T07:36:25.528293Z", "shell.execute_reply": "2025-03-25T07:36:25.528014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# Analyzing available demographic columns\n", "\n", "# For age columns\n", "age_columns = {'Age_at_Initial_Pathologic_Diagnosis_nature2012': [float('nan'), float('nan'), float('nan'), float('nan'), float('nan')], \n", " 'age_at_initial_pathologic_diagnosis': [55.0, 50.0, 62.0, 52.0, 50.0], \n", " 'days_to_birth': [-20211.0, -18538.0, -22848.0, -19074.0, -18371.0]}\n", "\n", "# For gender columns\n", "gender_columns = {'Gender_nature2012': [float('nan'), float('nan'), float('nan'), float('nan'), float('nan')], \n", " 'gender': ['FEMALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']}\n", "\n", "# Select age column - choose the one with non-NaN values\n", "age_col = None\n", "for col_name, values in age_columns.items():\n", " # Check if the column has non-NaN values\n", " if not all(pd.isna(val) for val in values):\n", " # Prefer direct age values over days_to_birth\n", " if 'age' in col_name.lower():\n", " age_col = col_name\n", " break\n", "\n", "# If no age column with 'age' in name found, consider days_to_birth\n", "if age_col is None and 'days_to_birth' in age_columns and not all(pd.isna(val) for val in age_columns['days_to_birth']):\n", " age_col = 'days_to_birth'\n", "\n", "# Select gender column - choose the one with non-NaN values\n", "gender_col = None\n", "for col_name, values in gender_columns.items():\n", " # Check if the column has non-NaN values\n", " if not all(pd.isna(val) for val in values):\n", " gender_col = col_name\n", " break\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": "21cc18c8", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "82f37bee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:25.529497Z", "iopub.status.busy": "2025-03-25T07:36:25.529388Z", "iopub.status.idle": "2025-03-25T07:38:03.424241Z", "shell.execute_reply": "2025-03-25T07:38:03.423858Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Longevity/gene_data/TCGA.csv\n", "Gene expression data shape after normalization: (19848, 1218)\n", "Clinical data saved to ../../output/preprocess/Longevity/clinical_data/TCGA.csv\n", "Clinical data shape: (1247, 3)\n", "Number of samples in clinical data: 1247\n", "Number of samples in genetic data: 1218\n", "Number of common samples: 1218\n", "Linked data shape: (1218, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (1218, 19851)\n", "For the feature 'Longevity', the least common label is '0' with 114 occurrences. This represents 9.36% of the dataset.\n", "The distribution of the feature 'Longevity' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 48.0\n", " 50% (Median): 58.0\n", " 75%: 67.0\n", "Min: 26.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 '1.0' with 13 occurrences. This represents 1.07% 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/Longevity/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 }