{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "b1e2e671", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:56.389916Z", "iopub.status.busy": "2025-03-25T06:58:56.389769Z", "iopub.status.idle": "2025-03-25T06:58:56.550137Z", "shell.execute_reply": "2025-03-25T06:58:56.549785Z" } }, "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 = \"Bladder_Cancer\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Bladder_Cancer/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Bladder_Cancer/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Bladder_Cancer/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Bladder_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "78da5baf", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "be5637fa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:56.551573Z", "iopub.status.busy": "2025-03-25T06:58:56.551436Z", "iopub.status.idle": "2025-03-25T06:58:57.587550Z", "shell.execute_reply": "2025-03-25T06:58:57.587192Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected directory: TCGA_Bladder_Cancer_(BLCA)\n", "Clinical file: TCGA.BLCA.sampleMap_BLCA_clinicalMatrix\n", "Genetic file: TCGA.BLCA.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_BLCA', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_BLCA', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_surgery_locoregional_procedure', 'additional_treatment_completion_success_outcome', 'age_at_initial_pathologic_diagnosis', 'age_began_smoking_in_years', 'anatomic_neoplasm_subdivision', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'bladder_carcinoma_extracapsular_extension_status', 'cancer_diagnosis_cancer_type_icd9_text_name', 'chemical_exposure_text', 'clinical_T', 'complete_response_observed', '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_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'diagnosis_subtype', 'disease_code', 'disease_extracapsular_extension_ind_3', 'eastern_cancer_oncology_group', 'family_member_relationship_type', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'hist_of_non_mibc', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'induction_course_complete', 'informed_consent_verified', 'init_pathology_dx_method_other', 'initial_pathologic_diagnosis_method', 'initial_weight', 'is_ffpe', 'karnofsky_performance_score', 'lost_follow_up', 'lymph_node_examined_count', 'lymphovascular_invasion_present', 'maint_therapy_course_complete', 'metastatic_site', 'mibc_90day_post_resection_bcg', 'neoplasm_histologic_grade', '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', 'non_mibc_tx', 'number_of_lymphnodes_positive_by_he', 'number_pack_years_smoked', 'occupation_primary_job', 'oct_embedded', 'other_dx', 'other_metastatic_site', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'person_concomitant_prostate_carcinoma_occurrence_indicator', 'person_concomitant_prostate_carcinoma_pathologic_t_stage', 'person_neoplasm_cancer_status', 'person_occupation_description_text', 'person_occupation_years_number', 'person_primary_industry_text', 'postoperative_rx_tx', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'project_code', 'radiation_therapy', 'resp_maint_from_bcg_admin_month_dur', 'sample_type', 'sample_type_id', 'stopped_smoking_year', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tobacco_smoking_history', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_BLCA_RPPA', '_GENOMIC_ID_TCGA_BLCA_mutation_curated_broad_gene', '_GENOMIC_ID_TCGA_BLCA_mutation', '_GENOMIC_ID_TCGA_BLCA_gistic2thd', '_GENOMIC_ID_TCGA_BLCA_RPPA_RBN', '_GENOMIC_ID_data/public/TCGA/BLCA/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_BLCA_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_BLCA_PDMRNAseq', '_GENOMIC_ID_TCGA_BLCA_mutation_broad_gene', '_GENOMIC_ID_data/public/TCGA/BLCA/miRNA_GA_gene', '_GENOMIC_ID_TCGA_BLCA_exp_HiSeqV2', '_GENOMIC_ID_TCGA_BLCA_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_BLCA_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_BLCA_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_BLCA_miRNA_HiSeq', '_GENOMIC_ID_TCGA_BLCA_miRNA_GA', '_GENOMIC_ID_TCGA_BLCA_hMethyl450', '_GENOMIC_ID_TCGA_BLCA_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_BLCA_gistic2']\n", "\n", "Clinical data shape: (436, 129)\n", "Genetic data shape: (20530, 426)\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# 1. Find the most relevant directory for Bladder Cancer\n", "subdirectories = os.listdir(tcga_root_dir)\n", "target_trait = trait.lower().replace(\"_\", \" \") # Convert to lowercase for case-insensitive matching\n", "\n", "# Search for exact matches or synonyms\n", "matched_dir = None\n", "for subdir in subdirectories:\n", " if \"bladder\" in subdir.lower() and \"cancer\" in subdir.lower():\n", " matched_dir = subdir\n", " break\n", "\n", "if not matched_dir:\n", " print(f\"No suitable directory found for {trait}.\")\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()\n", "\n", "print(f\"Selected directory: {matched_dir}\")\n", "\n", "# 2. Get the clinical and genetic data file paths\n", "cohort_dir = os.path.join(tcga_root_dir, matched_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" ] }, { "cell_type": "markdown", "id": "1760f433", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "7abdc56c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:57.588849Z", "iopub.status.busy": "2025-03-25T06:58:57.588739Z", "iopub.status.idle": "2025-03-25T06:58:57.599611Z", "shell.execute_reply": "2025-03-25T06:58:57.599330Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [63, 66, 69, 59, 83], 'age_began_smoking_in_years': [20.0, 15.0, nan, nan, 30.0], 'days_to_birth': [-23323.0, -24428.0, -25259.0, -21848.0, -30520.0]}\n", "\n", "Gender columns preview:\n", "{'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'MALE']}\n" ] } ], "source": [ "# Find candidate age columns\n", "candidate_age_cols = [\n", " 'age_at_initial_pathologic_diagnosis',\n", " 'age_began_smoking_in_years',\n", " 'days_to_birth' # This is often used to calculate age\n", "]\n", "\n", "# Find candidate gender columns\n", "candidate_gender_cols = [\n", " 'gender'\n", "]\n", "\n", "# Extract the candidate columns from clinical data\n", "# First, we need to load the clinical data\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Bladder_Cancer_(BLCA)\")\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n", "clinical_df = pd.read_table(clinical_file_path, index_col=0)\n", "\n", "# Extract and preview age columns\n", "age_data = clinical_df[candidate_age_cols]\n", "age_preview = preview_df(age_data, n=5)\n", "print(\"Age columns preview:\")\n", "print(age_preview)\n", "\n", "# Extract and preview gender columns\n", "gender_data = clinical_df[candidate_gender_cols]\n", "gender_preview = preview_df(gender_data, n=5)\n", "print(\"\\nGender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "7b4b5039", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "8fc76097", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:57.600706Z", "iopub.status.busy": "2025-03-25T06:58:57.600602Z", "iopub.status.idle": "2025-03-25T06:58:57.602789Z", "shell.execute_reply": "2025-03-25T06:58:57.602513Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# Step 1: Select appropriate columns for age and gender\n", "\n", "# For age, we have three candidate columns:\n", "# - 'age_at_initial_pathologic_diagnosis': Contains direct age values\n", "# - 'age_began_smoking_in_years': Contains smoking initiation age (many NaN values)\n", "# - 'days_to_birth': Contains negative values representing days before birth (essentially age in days)\n", "\n", "# Choose the most appropriate column for age\n", "age_col = 'age_at_initial_pathologic_diagnosis' # This column has clear, direct age values without NaNs\n", "\n", "# For gender, we only have one candidate column:\n", "# - 'gender': Contains 'MALE' and 'FEMALE' values\n", "gender_col = 'gender' # This is the only column and contains valid gender information\n", "\n", "# Step 2: 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": "ddc496fa", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "ed48391f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:57.604140Z", "iopub.status.busy": "2025-03-25T06:58:57.604041Z", "iopub.status.idle": "2025-03-25T06:59:36.281182Z", "shell.execute_reply": "2025-03-25T06:59:36.280608Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Bladder_Cancer/gene_data/TCGA.csv\n", "Gene expression data shape after normalization: (19848, 426)\n", "Clinical data saved to ../../output/preprocess/Bladder_Cancer/clinical_data/TCGA.csv\n", "Clinical data shape: (436, 3)\n", "Number of samples in clinical data: 436\n", "Number of samples in genetic data: 426\n", "Number of common samples: 426\n", "Linked data shape: (426, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (426, 19851)\n", "For the feature 'Bladder_Cancer', the least common label is '0' with 19 occurrences. This represents 4.46% of the dataset.\n", "The distribution of the feature 'Bladder_Cancer' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 60.0\n", " 50% (Median): 69.0\n", " 75%: 76.0\n", "Min: 34\n", "Max: 90\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 115 occurrences. This represents 27.00% 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/Bladder_Cancer/TCGA.csv\n", "Preprocessing completed.\n" ] } ], "source": [ "# Step 1: Extract and standardize clinical features\n", "# Create clinical features dataframe with trait (bladder cancer) using patient IDs\n", "clinical_features = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=\"Bladder_Cancer\", \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=\"Bladder_Cancer\")\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=\"Bladder_Cancer\")\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=\"Dataset contains TCGA bladder cancer samples with gene expression and clinical information.\"\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 }