{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "e550d8b4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:47.045292Z", "iopub.status.busy": "2025-03-25T07:02:47.045046Z", "iopub.status.idle": "2025-03-25T07:02:47.214574Z", "shell.execute_reply": "2025-03-25T07:02:47.214122Z" } }, "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 = \"Breast_Cancer\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Breast_Cancer/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "729d70f2", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0f8f803b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:47.216111Z", "iopub.status.busy": "2025-03-25T07:02:47.215958Z", "iopub.status.idle": "2025-03-25T07:02:50.199244Z", "shell.execute_reply": "2025-03-25T07:02:50.198571Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Looking for a relevant cohort directory for Breast_Cancer...\n", "Available cohorts: ['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", "Breast cancer-related cohorts: ['TCGA_Breast_Cancer_(BRCA)']\n", "Selected cohort: TCGA_Breast_Cancer_(BRCA)\n", "Clinical data file: TCGA.BRCA.sampleMap_BRCA_clinicalMatrix\n", "Genetic data 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" ] } ], "source": [ "import os\n", "\n", "# Check if there's a suitable cohort directory for Breast_Cancer\n", "print(f\"Looking for a relevant cohort directory for {trait}...\")\n", "\n", "# Check available cohorts\n", "available_dirs = os.listdir(tcga_root_dir)\n", "print(f\"Available cohorts: {available_dirs}\")\n", "\n", "# Breast cancer-related keywords\n", "breast_cancer_keywords = ['breast', 'mammary', 'brca']\n", "\n", "# Look for breast cancer-related directories\n", "breast_cancer_related_dirs = []\n", "for d in available_dirs:\n", " if any(keyword in d.lower() for keyword in breast_cancer_keywords):\n", " breast_cancer_related_dirs.append(d)\n", "\n", "print(f\"Breast cancer-related cohorts: {breast_cancer_related_dirs}\")\n", "\n", "if not breast_cancer_related_dirs:\n", " print(f\"No suitable cohort found for {trait}.\")\n", " # Mark the task as completed by recording the unavailability\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", " # Exit the script early since no suitable cohort was found\n", " selected_cohort = None\n", "else:\n", " # For breast cancer, the BRCA dataset is most relevant\n", " if 'TCGA_Breast_Cancer_(BRCA)' in breast_cancer_related_dirs:\n", " selected_cohort = 'TCGA_Breast_Cancer_(BRCA)'\n", " else:\n", " selected_cohort = breast_cancer_related_dirs[0] # Use the first match if the preferred one isn't available\n", "\n", "if selected_cohort:\n", " print(f\"Selected cohort: {selected_cohort}\")\n", " \n", " # Get the full path to the selected cohort directory\n", " cohort_dir = os.path.join(tcga_root_dir, selected_cohort)\n", " \n", " # Get the clinical and genetic data file paths\n", " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", " \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", " # Load the 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 the column names of the clinical data\n", " print(\"\\nClinical data columns:\")\n", " print(clinical_df.columns.tolist())\n", " \n", " # Basic info about the datasets\n", " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n", " print(f\"Genetic data shape: {genetic_df.shape}\")\n" ] }, { "cell_type": "markdown", "id": "46aaa1a5", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "2e9d2561", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:50.201465Z", "iopub.status.busy": "2025-03-25T07:02:50.201325Z", "iopub.status.idle": "2025-03-25T07:02:50.225504Z", "shell.execute_reply": "2025-03-25T07:02:50.224944Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age-related 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-related columns preview:\n", "{'Gender_nature2012': [nan, nan, nan, nan, nan], 'gender': ['FEMALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Extract clinical data file path\n", "tcga_cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Breast_Cancer_(BRCA)\")\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(tcga_cohort_dir)\n", "\n", "# Load clinical data\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Identify age-related columns\n", "candidate_age_cols = [\n", " 'Age_at_Initial_Pathologic_Diagnosis_nature2012',\n", " 'age_at_initial_pathologic_diagnosis',\n", " 'days_to_birth' # Age can be calculated from days to birth\n", "]\n", "\n", "# Identify gender-related columns\n", "candidate_gender_cols = [\n", " 'Gender_nature2012',\n", " 'gender'\n", "]\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", "print(\"Age-related columns preview:\")\n", "print(age_preview)\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(\"\\nGender-related columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "3bed22ef", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "17aceb0f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:50.227462Z", "iopub.status.busy": "2025-03-25T07:02:50.227333Z", "iopub.status.idle": "2025-03-25T07:02:50.231860Z", "shell.execute_reply": "2025-03-25T07:02:50.231319Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Chosen age column: age_at_initial_pathologic_diagnosis\n", "Chosen gender column: gender\n" ] } ], "source": [ "# Analyze age-related columns\n", "age_col = None\n", "# Check each age-related column\n", "if 'age_at_initial_pathologic_diagnosis' in age_preview and not all(pd.isna(age_preview['age_at_initial_pathologic_diagnosis'])):\n", " age_col = 'age_at_initial_pathologic_diagnosis'\n", "elif 'days_to_birth' in age_preview and not all(pd.isna(age_preview['days_to_birth'])):\n", " age_col = 'days_to_birth'\n", "elif 'Age_at_Initial_Pathologic_Diagnosis_nature2012' in age_preview and not all(pd.isna(age_preview['Age_at_Initial_Pathologic_Diagnosis_nature2012'])):\n", " age_col = 'Age_at_Initial_Pathologic_Diagnosis_nature2012'\n", "\n", "# Analyze gender-related columns\n", "gender_col = None\n", "# Check each gender-related column\n", "if 'gender' in gender_preview and not all(pd.isna(gender_preview['gender'])):\n", " gender_col = 'gender'\n", "elif 'Gender_nature2012' in gender_preview and not all(pd.isna(gender_preview['Gender_nature2012'])):\n", " gender_col = 'Gender_nature2012'\n", "\n", "# Print the chosen columns\n", "print(f\"Chosen age column: {age_col}\")\n", "print(f\"Chosen gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "91c88c60", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "c4b59b02", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:50.233811Z", "iopub.status.busy": "2025-03-25T07:02:50.233668Z", "iopub.status.idle": "2025-03-25T07:04:50.904147Z", "shell.execute_reply": "2025-03-25T07:04:50.903515Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features (first 5 rows):\n", " Breast_Cancer Age Gender\n", "sampleID \n", "TCGA-3C-AAAU-01 1 55.0 0.0\n", "TCGA-3C-AALI-01 1 50.0 0.0\n", "TCGA-3C-AALJ-01 1 62.0 0.0\n", "TCGA-3C-AALK-01 1 52.0 0.0\n", "TCGA-4H-AAAK-01 1 50.0 0.0\n", "\n", "Processing gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original gene data shape: (20530, 1218)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Attempting to normalize gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (19848, 1218)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to: ../../output/preprocess/Breast_Cancer/gene_data/TCGA.csv\n", "\n", "Linking clinical and genetic data...\n", "Clinical data shape: (1247, 3)\n", "Genetic data shape: (19848, 1218)\n", "Number of common samples: 1218\n", "\n", "Linked data shape: (1218, 19851)\n", "Linked data preview (first 5 rows, first few columns):\n", " Breast_Cancer Age Gender A1BG A1BG-AS1\n", "TCGA-A2-A25B-01 1 39.0 0.0 -0.599274 0.350817\n", "TCGA-BH-A0B8-11 0 64.0 0.0 -1.825574 -0.860783\n", "TCGA-S3-AA11-01 1 67.0 0.0 0.593526 1.069817\n", "TCGA-AN-A0FN-01 1 61.0 0.0 -0.471074 1.121317\n", "TCGA-GM-A2D9-01 1 69.0 0.0 2.970626 1.559317\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Data shape after handling missing values: (1218, 19851)\n", "\n", "Checking for bias in features:\n", "For the feature 'Breast_Cancer', the least common label is '0' with 114 occurrences. This represents 9.36% of the dataset.\n", "The distribution of the feature 'Breast_Cancer' 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", "\n", "Performing final validation...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to: ../../output/preprocess/Breast_Cancer/TCGA.csv\n", "Clinical data saved to: ../../output/preprocess/Breast_Cancer/clinical_data/TCGA.csv\n" ] } ], "source": [ "# 1. Extract and standardize clinical features\n", "# Use tcga_select_clinical_features which will automatically create the trait variable and add age/gender if provided\n", "# Use the correct cohort identified in Step 1\n", "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Breast_Cancer_(BRCA)')\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Load the clinical data if not already loaded\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "linked_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", "# Print preview of clinical features\n", "print(\"Clinical features (first 5 rows):\")\n", "print(linked_clinical_df.head())\n", "\n", "# 2. Process gene expression data\n", "print(\"\\nProcessing gene expression data...\")\n", "# Load genetic data from the same cohort directory\n", "genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n", "\n", "# Check gene data shape\n", "print(f\"Original gene data shape: {genetic_df.shape}\")\n", "\n", "# Save a version of the gene data before normalization (as a backup)\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "genetic_df.to_csv(out_gene_data_file.replace('.csv', '_original.csv'))\n", "\n", "# We need to transpose genetic data so genes are rows and samples are columns for normalization\n", "gene_df_for_norm = genetic_df.copy() # Keep original orientation for now\n", "\n", "# Try to normalize gene symbols - adding debug output to understand what's happening\n", "print(\"Attempting to normalize gene symbols...\")\n", "try:\n", " # First check if we need to transpose based on the data format\n", " # In TCGA data, typically genes are rows and samples are columns\n", " if gene_df_for_norm.shape[0] > gene_df_for_norm.shape[1]:\n", " # More rows than columns, likely genes are rows already\n", " normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm)\n", " else:\n", " # Need to transpose first\n", " normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm.T)\n", " \n", " print(f\"Gene data shape after normalization: {normalized_gene_df.shape}\")\n", " \n", " # Check if normalization returned empty DataFrame\n", " if normalized_gene_df.shape[0] == 0:\n", " print(\"WARNING: Gene symbol normalization returned an empty DataFrame.\")\n", " print(\"Using original gene data instead of normalized data.\")\n", " # Use original data\n", " normalized_gene_df = genetic_df\n", " \n", "except Exception as e:\n", " print(f\"Error during gene symbol normalization: {e}\")\n", " print(\"Using original gene data instead.\")\n", " normalized_gene_df = genetic_df\n", "\n", "# Save gene data\n", "normalized_gene_df.to_csv(out_gene_data_file)\n", "print(f\"Gene data saved to: {out_gene_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "# TCGA data uses the same sample IDs in both datasets\n", "print(\"\\nLinking clinical and genetic data...\")\n", "print(f\"Clinical data shape: {linked_clinical_df.shape}\")\n", "print(f\"Genetic data shape: {normalized_gene_df.shape}\")\n", "\n", "# Find common samples between clinical and genetic data\n", "# In TCGA, samples are typically columns in the gene data and index in the clinical data\n", "common_samples = set(linked_clinical_df.index).intersection(set(normalized_gene_df.columns))\n", "print(f\"Number of common samples: {len(common_samples)}\")\n", "\n", "if len(common_samples) == 0:\n", " print(\"ERROR: No common samples found between clinical and genetic data.\")\n", " # Try the alternative orientation\n", " common_samples = set(linked_clinical_df.index).intersection(set(normalized_gene_df.index))\n", " print(f\"Checking alternative orientation: {len(common_samples)} common samples found.\")\n", " \n", " if len(common_samples) == 0:\n", " # Use is_final=False mode which doesn't require df and is_biased\n", " validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=True\n", " )\n", " print(\"The dataset was determined to be unusable for this trait due to no common samples. No data files were saved.\")\n", "else:\n", " # Filter clinical data to only include common samples\n", " linked_clinical_df = linked_clinical_df.loc[list(common_samples)]\n", " \n", " # Create linked data by merging\n", " linked_data = pd.concat([linked_clinical_df, normalized_gene_df[list(common_samples)].T], axis=1)\n", " \n", " print(f\"\\nLinked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first few columns):\")\n", " display_cols = [trait, 'Age', 'Gender'] + list(linked_data.columns[3:5])\n", " print(linked_data[display_cols].head())\n", " \n", " # 4. Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"\\nData shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 5. Check for bias in features\n", " print(\"\\nChecking for bias in features:\")\n", " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # 6. Validate and save cohort info\n", " print(\"\\nPerforming final validation...\")\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(linked_data.columns) > 3, # More than just trait/age/gender columns\n", " is_trait_available=trait in linked_data.columns,\n", " is_biased=is_trait_biased,\n", " df=linked_data,\n", " note=\"Data from TCGA Breast Cancer (BRCA) cohort used for breast cancer analysis.\"\n", " )\n", " \n", " # 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", " \n", " # Also save clinical data separately\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_columns = [col for col in linked_data.columns if col in [trait, 'Age', 'Gender']]\n", " linked_data[clinical_columns].to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n", " else:\n", " print(\"The dataset was determined to be unusable for this trait. No data files were 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 }