{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "5226926e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:56.544108Z", "iopub.status.busy": "2025-03-25T08:14:56.543871Z", "iopub.status.idle": "2025-03-25T08:14:56.708951Z", "shell.execute_reply": "2025-03-25T08:14:56.708510Z" } }, "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 = \"Cervical_Cancer\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Cervical_Cancer/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Cervical_Cancer/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Cervical_Cancer/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Cervical_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "4b73f5a7", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ac34519a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:56.710401Z", "iopub.status.busy": "2025-03-25T08:14:56.710258Z", "iopub.status.idle": "2025-03-25T08:14:57.505331Z", "shell.execute_reply": "2025-03-25T08:14:57.504644Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found potential match: TCGA_Cervical_Cancer_(CESC)\n", "Selected as best match: TCGA_Cervical_Cancer_(CESC)\n", "Selected directory: TCGA_Cervical_Cancer_(CESC)\n", "Clinical file: TCGA.CESC.sampleMap_CESC_clinicalMatrix\n", "Genetic file: TCGA.CESC.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', 'additional_treatment_completion_success_outcome', 'adjuvant_rad_therapy_prior_admin', 'age_at_initial_pathologic_diagnosis', 'age_began_smoking_in_years', 'agent_total_dose_count', 'assessment_timepoint_category', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'birth_control_pill_history_usage_category', 'brachytherapy_administered_status', 'brachytherapy_first_reference_point_administered_total_dose', 'brachytherapy_method_other_specify_text', 'brachytherapy_method_type', 'cervical_carcinoma_corpus_uteri_involvement_indicator', 'cervical_carcinoma_pelvic_extension_text', 'cervical_neoplasm_pathologic_margin_involved_text', 'cervical_neoplasm_pathologic_margin_involved_type', 'chemotherapy_negation_radiation_therapy_concurrent_adminstrd_txt', 'chemotherapy_negation_radiation_therapy_concurrnt_nt_dmnstrd_rsn', 'chemotherapy_regimen_type', 'clinical_stage', 'concurrent_chemotherapy_dose', 'days_to_birth', 'days_to_brachytherapy_begin_occurrence', 'days_to_brachytherapy_end_occurrence', 'days_to_chemotherapy_end', 'days_to_chemotherapy_start', 'days_to_collection', 'days_to_death', 'days_to_diagnostic_computed_tomography_performed', 'days_to_diagnostic_mri_performed', 'days_to_fdg_or_ct_pet_performed', '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', 'days_to_performance_status_assessment', 'days_to_radiation_therapy_end', 'days_to_radiation_therapy_start', 'death_cause_text', 'diagnostic_ct_result_outcome', 'diagnostic_mri_result_outcome', 'dose_frequency_text', 'eastern_cancer_oncology_group', 'ectopic_pregnancy_count', 'external_beam_radiation_therapy_administered_status', 'external_beam_radiation_therapy_administrd_prrtc_rgn_lymph_nd_ds', 'fdg_or_ct_pet_performed_outcome', 'female_breast_feeding_or_pregnancy_status_indicator', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_of_neoadjuvant_treatment', 'human_papillomavirus_laboratory_procedure_performed_name', 'human_papillomavirus_laboratory_procedure_performed_text', 'human_papillomavirus_other_type_text', 'human_papillomavirus_type', 'hysterectomy_performed_text', 'hysterectomy_performed_type', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'init_pathology_dx_method_other', 'initial_pathologic_diagnosis_method', 'initial_weight', 'is_ffpe', 'keratinizing_squamous_cell_carcinoma_present_indicator', 'lost_follow_up', 'lymph_node_examined_count', 'lymph_node_location_positive_pathology_name', 'lymph_node_location_positive_pathology_text', 'lymphovascular_invasion_indicator', 'menopause_status', 'neoplasm_histologic_grade', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_post_initial_therapy_diagnosis_method_text', 'new_neoplasm_event_post_initial_therapy_diagnosis_method_type', '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', 'number_of_successful_pregnancies_which_resultd_n_t_lst_1_lv_brth', 'number_pack_years_smoked', 'oct_embedded', 'oligonucleotide_primer_pair_laboratory_procedure_performed_name', 'other_chemotherapy_agent_administration_specify', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathology_report_file_name', 'patient_death_reason', 'patient_history_immune_system_and_related_disorders_name', 'patient_history_immune_system_and_related_disorders_text', 'patient_id', 'patient_pregnancy_spontaneous_abortion_count', 'patient_pregnancy_therapeutic_abortion_count', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'pregnancy_stillbirth_count', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'radiation_therapy', 'radiation_therapy_not_administered_reason', 'radiation_therapy_not_administered_specify', 'radiation_type_notes', 'residual_disease_post_new_tumor_event_margin_status', 'rt_administered_type', 'rt_pelvis_administered_total_dose', 'sample_type', 'sample_type_id', 'standardized_uptake_value_cervix_uteri_assessment_measurement', 'stopped_smoking_year', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tobacco_smoking_history', 'total_number_of_pregnancies', 'tumor_response_cdus_type', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_CESC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_data/public/TCGA/CESC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_CESC_PDMRNAseq', '_GENOMIC_ID_TCGA_CESC_RPPA', '_GENOMIC_ID_TCGA_CESC_hMethyl450', '_GENOMIC_ID_TCGA_CESC_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_CESC_mutation', '_GENOMIC_ID_TCGA_CESC_mutation_broad_gene', '_GENOMIC_ID_TCGA_CESC_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_CESC_mutation_curated_wustl_gene', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_CESC_gistic2', '_GENOMIC_ID_TCGA_CESC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_CESC_gistic2thd']\n", "\n", "Clinical data shape: (313, 157)\n", "Genetic data shape: (20530, 308)\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# 1. Find the most relevant directory for Cervical 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 related terms to Cervical Cancer\n", "related_terms = [\"cervical\", \"cervix\", \"cesc\"]\n", "matched_dir = None\n", "\n", "for subdir in subdirectories:\n", " subdir_lower = subdir.lower()\n", " # Check if any related term is in the directory name\n", " if any(term in subdir_lower for term in related_terms):\n", " matched_dir = subdir\n", " print(f\"Found potential match: {subdir}\")\n", " # If exact match found, select it\n", " if \"cervical_cancer\" in subdir_lower.replace(\" \", \"_\"):\n", " print(f\"Selected as best match: {subdir}\")\n", " matched_dir = subdir\n", " break\n", "\n", "# If we found a potential match, use it\n", "if matched_dir:\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", " \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 matched_dir:\n", " print(\"Skipping this trait as no suitable data was found.\")\n" ] }, { "cell_type": "markdown", "id": "86393b98", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "a060f7a3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:57.507321Z", "iopub.status.busy": "2025-03-25T08:14:57.507151Z", "iopub.status.idle": "2025-03-25T08:14:57.518214Z", "shell.execute_reply": "2025-03-25T08:14:57.517726Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [51.0, 31.0, 53.0, 48.0, 49.0], 'age_began_smoking_in_years': [nan, nan, 22.0, nan, nan], 'days_to_birth': [-18886.0, -11611.0, -19473.0, -17839.0, -18215.0]}\n", "\n", "Gender columns preview:\n", "{'gender': ['FEMALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# 1. Identify candidate columns for age and gender\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, \"TCGA_Cervical_Cancer_(CESC)\"))\n", "clinical_data = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Candidate columns for age and gender\n", "candidate_age_cols = [\n", " 'age_at_initial_pathologic_diagnosis', \n", " 'age_began_smoking_in_years', \n", " 'days_to_birth'\n", "]\n", "candidate_gender_cols = ['gender']\n", "\n", "# 2. Preview the candidate columns\n", "age_preview = {}\n", "for col in candidate_age_cols:\n", " if col in clinical_data.columns:\n", " age_preview[col] = clinical_data[col].head(5).tolist()\n", "\n", "gender_preview = {}\n", "for col in candidate_gender_cols:\n", " if col in clinical_data.columns:\n", " gender_preview[col] = clinical_data[col].head(5).tolist()\n", "\n", "print(\"Age columns preview:\")\n", "print(age_preview)\n", "print(\"\\nGender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "86c70047", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "f9300dc5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:57.519832Z", "iopub.status.busy": "2025-03-25T08:14:57.519716Z", "iopub.status.idle": "2025-03-25T08:14:57.523217Z", "shell.execute_reply": "2025-03-25T08:14:57.522748Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selecting demographic columns for age and gender information:\n", "- age_at_initial_pathologic_diagnosis: Contains direct age values\n", "- age_began_smoking_in_years: Contains age when patient started smoking (too many NaN values)\n", "- days_to_birth: Contains negative days (days from birth to diagnosis date)\n", "- gender: Contains direct gender information (FEMALE/MALE)\n", "\n", "Selected demographic columns:\n", "Age column: age_at_initial_pathologic_diagnosis\n", "Gender column: gender\n" ] } ], "source": [ "# Examine age columns\n", "print(\"Selecting demographic columns for age and gender information:\")\n", "\n", "age_cols_info = {\n", " 'age_at_initial_pathologic_diagnosis': \"Contains direct age values\",\n", " 'age_began_smoking_in_years': \"Contains age when patient started smoking (too many NaN values)\",\n", " 'days_to_birth': \"Contains negative days (days from birth to diagnosis date)\"\n", "}\n", "\n", "for col, desc in age_cols_info.items():\n", " print(f\"- {col}: {desc}\")\n", "\n", "# Select the most appropriate age column\n", "# 'age_at_initial_pathologic_diagnosis' is the best choice as it directly contains patient age\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# Examine gender columns\n", "gender_cols_info = {\n", " 'gender': \"Contains direct gender information (FEMALE/MALE)\"\n", "}\n", "\n", "for col, desc in gender_cols_info.items():\n", " print(f\"- {col}: {desc}\")\n", "\n", "# Select the gender column\n", "gender_col = 'gender'\n", "\n", "# Print the selected columns\n", "print(\"\\nSelected demographic columns:\")\n", "print(f\"Age column: {age_col}\")\n", "print(f\"Gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "bd183d17", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "51a78be2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:14:57.524709Z", "iopub.status.busy": "2025-03-25T08:14:57.524601Z", "iopub.status.idle": "2025-03-25T08:15:08.116180Z", "shell.execute_reply": "2025-03-25T08:15:08.115534Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Cervical_Cancer/gene_data/TCGA.csv\n", "Gene expression data shape after normalization: (19848, 308)\n", "Clinical data saved to ../../output/preprocess/Cervical_Cancer/clinical_data/TCGA.csv\n", "Clinical data shape: (313, 3)\n", "Number of samples in clinical data: 313\n", "Number of samples in genetic data: 308\n", "Number of common samples: 308\n", "Linked data shape: (308, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (308, 19851)\n", "For the feature 'Cervical_Cancer', the least common label is '0' with 3 occurrences. This represents 0.97% of the dataset.\n", "The distribution of the feature 'Cervical_Cancer' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 38.0\n", " 50% (Median): 46.0\n", " 75%: 56.0\n", "Min: 20.0\n", "Max: 88.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 308 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Dataset deemed not usable based on validation criteria. Data not saved.\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 }