{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "9841992c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:06.187959Z", "iopub.status.busy": "2025-03-25T05:41:06.187789Z", "iopub.status.idle": "2025-03-25T05:41:06.353142Z", "shell.execute_reply": "2025-03-25T05:41:06.352818Z" } }, "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 = \"Hemochromatosis\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hemochromatosis/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hemochromatosis/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hemochromatosis/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Hemochromatosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "15470262", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "1b0c1e62", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:06.354939Z", "iopub.status.busy": "2025-03-25T05:41:06.354783Z", "iopub.status.idle": "2025-03-25T05:41:07.360012Z", "shell.execute_reply": "2025-03-25T05:41:07.359678Z" } }, "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", "Found potential match: TCGA_Liver_Cancer_(LIHC) (score: 1)\n", "Selected directory: TCGA_Liver_Cancer_(LIHC)\n", "Clinical file: TCGA.LIHC.sampleMap_LIHC_clinicalMatrix\n", "Genetic file: TCGA.LIHC.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'adjacent_hepatic_tissue_inflammation_extent_type', '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', 'cancer_first_degree_relative', 'child_pugh_classification_grade', '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_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'eastern_cancer_oncology_group', 'fetoprotein_outcome_lower_limit', 'fetoprotein_outcome_upper_limit', 'fetoprotein_outcome_value', 'fibrosis_ishak_score', 'followup_case_report_form_submission_reason', '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_neoplasm_occurrence_anatomic_site_text', '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', '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_disease_post_new_tumor_event_margin_status', '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', 'viral_hepatitis_serology', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_LIHC_gistic2', '_GENOMIC_ID_TCGA_LIHC_gistic2thd', '_GENOMIC_ID_TCGA_LIHC_mutation_bcm_gene', '_GENOMIC_ID_TCGA_LIHC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_LIHC_PDMRNAseq', '_GENOMIC_ID_TCGA_LIHC_RPPA', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_LIHC_mutation_bcgsc_gene', '_GENOMIC_ID_data/public/TCGA/LIHC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_LIHC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LIHC_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LIHC_mutation_broad_gene', '_GENOMIC_ID_TCGA_LIHC_hMethyl450']\n", "\n", "Clinical data shape: (438, 109)\n", "Genetic data shape: (20530, 423)\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 Hemochromatosis\n", "# Define key terms relevant to Hemochromatosis\n", "key_terms = [\"liver\", \"iron\", \"hemochromatosis\", \"hepatic\", \"metal\", \"LIHC\"]\n", "\n", "# Initialize variables for best match\n", "best_match = None\n", "best_match_score = 0\n", "min_threshold = 1 # Require at least 1 matching term\n", "\n", "# Convert trait to lowercase for case-insensitive matching\n", "target_trait = trait.lower() # \"hemochromatosis\"\n", "\n", "# Search for relevant directories\n", "for subdir in subdirectories:\n", " if not os.path.isdir(os.path.join(tcga_root_dir, subdir)) or subdir.startswith('.'):\n", " continue\n", " \n", " subdir_lower = subdir.lower()\n", " \n", " # Check for exact matches\n", " if target_trait in subdir_lower:\n", " best_match = subdir\n", " print(f\"Found exact match: {subdir}\")\n", " break\n", " \n", " # Calculate score based on key terms\n", " score = 0\n", " for term in key_terms:\n", " if term in subdir_lower:\n", " score += 1\n", " \n", " # Update best match if score is higher than current best\n", " if score > best_match_score and score >= min_threshold:\n", " best_match_score = score\n", " best_match = subdir\n", " print(f\"Found potential match: {subdir} (score: {score})\")\n", "\n", "# If no match found, LIHC (Liver Cancer) is most relevant for Hemochromatosis\n", "if not best_match and \"TCGA_Liver_Cancer_(LIHC)\" in subdirectories:\n", " best_match = \"TCGA_Liver_Cancer_(LIHC)\"\n", " print(f\"Selected {best_match} as most relevant to Hemochromatosis which affects the liver\")\n", "\n", "# Handle the case where a match is found\n", "if best_match:\n", " print(f\"Selected directory: {best_match}\")\n", " \n", " # 2. Get the clinical and genetic data file paths\n", " cohort_dir = os.path.join(tcga_root_dir, best_match)\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 we have both gene and trait data\n", " is_gene_available = genetic_df.shape[0] > 0\n", " is_trait_available = clinical_df.shape[0] > 0\n", " \n", "else:\n", " print(f\"No suitable directory found for {trait}.\")\n", " is_gene_available = False\n", " is_trait_available = False\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 best_match:\n", " print(\"Skipping this trait as no suitable data was found in TCGA.\")\n" ] }, { "cell_type": "markdown", "id": "3feef701", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "2ae04b96", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:07.361349Z", "iopub.status.busy": "2025-03-25T05:41:07.361240Z", "iopub.status.idle": "2025-03-25T05:41:07.371119Z", "shell.execute_reply": "2025-03-25T05:41:07.370815Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [nan, 58.0, 51.0, 55.0, 54.0], 'days_to_birth': [nan, -21318.0, -18768.0, -20187.0, -20011.0]}\n", "Gender columns preview:\n", "{'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Examine the clinical data columns to identify candidate age and gender columns\n", "candidate_age_cols = [\"age_at_initial_pathologic_diagnosis\", \"days_to_birth\"]\n", "candidate_gender_cols = [\"gender\"]\n", "\n", "# Let's get the clinical data file path first\n", "lihc_dir = os.path.join(tcga_root_dir, \"TCGA_Liver_Cancer_(LIHC)\")\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(lihc_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 the age columns\n", "age_preview = {}\n", "if candidate_age_cols:\n", " age_data = clinical_df[candidate_age_cols]\n", " age_preview = preview_df(age_data)\n", " print(\"Age columns preview:\")\n", " print(age_preview)\n", "\n", "# Extract and preview the gender columns\n", "gender_preview = {}\n", "if candidate_gender_cols:\n", " gender_data = clinical_df[candidate_gender_cols]\n", " gender_preview = preview_df(gender_data)\n", " print(\"Gender columns preview:\")\n", " print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "9d3a4aae", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "be4d3a61", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:07.372312Z", "iopub.status.busy": "2025-03-25T05:41:07.372210Z", "iopub.status.idle": "2025-03-25T05:41:07.374506Z", "shell.execute_reply": "2025-03-25T05:41:07.374222Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Chosen age column: age_at_initial_pathologic_diagnosis\n", "Age column preview: {'age_at_initial_pathologic_diagnosis': [nan, 58.0, 51.0, 55.0, 54.0]}\n", "Chosen gender column: gender\n", "Gender column preview: {'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Select appropriate columns for age and gender based on the provided previews\n", "\n", "# For age:\n", "# Both 'age_at_initial_pathologic_diagnosis' and 'days_to_birth' contain meaningful data\n", "# 'age_at_initial_pathologic_diagnosis' directly gives age in years, which is more intuitive\n", "# 'days_to_birth' gives negative days since birth, which would need conversion\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# For gender:\n", "# Only one column is available and it has meaningful values (MALE/FEMALE)\n", "gender_col = 'gender'\n", "\n", "# Print chosen columns\n", "print(f\"Chosen age column: {age_col}\")\n", "print(f\"Age column preview: {{'age_at_initial_pathologic_diagnosis': [nan, 58.0, 51.0, 55.0, 54.0]}}\")\n", "\n", "print(f\"Chosen gender column: {gender_col}\")\n", "print(f\"Gender column preview: {{'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}}\")\n" ] }, { "cell_type": "markdown", "id": "78e95949", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "b204cfcc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:41:07.375611Z", "iopub.status.busy": "2025-03-25T05:41:07.375514Z", "iopub.status.idle": "2025-03-25T05:41:47.154799Z", "shell.execute_reply": "2025-03-25T05:41:47.154092Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Hemochromatosis/gene_data/TCGA.csv\n", "Gene expression data shape after normalization: (19848, 423)\n", "Clinical data saved to ../../output/preprocess/Hemochromatosis/clinical_data/TCGA.csv\n", "Clinical data shape: (438, 3)\n", "Number of samples in clinical data: 438\n", "Number of samples in genetic data: 423\n", "Number of common samples: 423\n", "Linked data shape: (423, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (423, 19851)\n", "For the feature 'Hemochromatosis', the least common label is '0' with 50 occurrences. This represents 11.82% of the dataset.\n", "The distribution of the feature 'Hemochromatosis' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 52.0\n", " 50% (Median): 62.0\n", " 75%: 69.0\n", "Min: 16.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' with 143 occurrences. This represents 33.81% 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/Hemochromatosis/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 }