{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a7767e9f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:54.782788Z", "iopub.status.busy": "2025-03-25T03:47:54.782558Z", "iopub.status.idle": "2025-03-25T03:47:54.946349Z", "shell.execute_reply": "2025-03-25T03:47:54.946021Z" } }, "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 = \"Rectal_Cancer\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Rectal_Cancer/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Rectal_Cancer/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Rectal_Cancer/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Rectal_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "22a9728b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "5d713370", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:54.947838Z", "iopub.status.busy": "2025-03-25T03:47:54.947699Z", "iopub.status.idle": "2025-03-25T03:47:55.236638Z", "shell.execute_reply": "2025-03-25T03:47:55.236311Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found matching directories: ['TCGA_Rectal_Cancer_(READ)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)']\n", "Selected directory: TCGA_Rectal_Cancer_(READ)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Clinical data columns:\n", "['AWG_MLH1_silencing', 'AWG_cancer_type_Oct62011', 'CDE_ID_3226963', 'CIMP', 'MSI_updated_Oct62011', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_READ', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'anatomic_neoplasm_subdivision', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'braf_gene_analysis_performed', 'braf_gene_analysis_result', 'circumferential_resection_margin', 'colon_polyps_present', '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', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_of_colon_polyps', 'history_of_neoadjuvant_treatment', 'hypermutation', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'kras_gene_analysis_performed', 'kras_mutation_codon', 'kras_mutation_found', 'longest_dimension', 'loss_expression_of_mismatch_repair_proteins_by_ihc', 'loss_expression_of_mismatch_repair_proteins_by_ihc_result', 'lost_follow_up', 'lymph_node_examined_count', 'lymphatic_invasion', 'microsatellite_instability', 'new_neoplasm_event_type', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'non_nodal_tumor_deposits', 'non_silent_mutation', 'non_silent_rate_per_Mb', 'number_of_abnormal_loci', 'number_of_first_degree_relatives_with_cancer_diagnosis', 'number_of_loci_tested', 'number_of_lymphnodes_positive_by_he', 'number_of_lymphnodes_positive_by_ihc', 'oct_embedded', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'perineural_invasion_present', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'preoperative_pretreatment_cea_level', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'radiation_therapy', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'silent_mutation', 'silent_rate_per_Mb', 'site_of_additional_surgery_new_tumor_event_mets', 'synchronous_colon_cancer_present', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_mutation', 'tumor_tissue_site', 'venous_invasion', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_READ_RPPA', '_GENOMIC_ID_TCGA_READ_G4502A_07_3', '_GENOMIC_ID_TCGA_READ_exp_HiSeqV2', '_GENOMIC_ID_TCGA_READ_PDMarrayCNV', '_GENOMIC_ID_TCGA_READ_PDMRNAseq', '_GENOMIC_ID_TCGA_READ_miRNA_GA', '_GENOMIC_ID_TCGA_READ_exp_GAV2', '_GENOMIC_ID_TCGA_READ_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_READ_hMethyl27', '_GENOMIC_ID_TCGA_READ_miRNA_HiSeq', '_GENOMIC_ID_TCGA_READ_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_READ_mutation_bcm_gene', '_GENOMIC_ID_TCGA_READ_hMethyl450', '_GENOMIC_ID_TCGA_READ_gistic2', '_GENOMIC_ID_TCGA_READ_RPPA_RBN', '_GENOMIC_ID_data/public/TCGA/READ/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_READ_PDMarray', '_GENOMIC_ID_data/public/TCGA/READ/miRNA_GA_gene', '_GENOMIC_ID_TCGA_READ_gistic2thd', '_GENOMIC_ID_TCGA_READ_exp_GAV2_exon', '_GENOMIC_ID_TCGA_READ_mutation_bcm_solid_gene', '_GENOMIC_ID_TCGA_READ_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_READ_exp_HiSeqV2_exon']\n" ] } ], "source": [ "# Step 1: Search for directories related to Rectal Cancer\n", "import os\n", "\n", "# List all directories in TCGA root directory\n", "tcga_dirs = os.listdir(tcga_root_dir)\n", "\n", "# Look for directories related to Rectal Cancer\n", "matching_dirs = [dir_name for dir_name in tcga_dirs \n", " if any(term in dir_name.lower() for term in \n", " [\"rectal\", \"read\", \"coadread\"])]\n", "\n", "if not matching_dirs:\n", " print(f\"No matching directory found for trait: {trait}\")\n", " \n", " # Record that this trait is not available and exit\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", " print(f\"Task marked as completed. {trait} is not directly represented in the TCGA dataset.\")\n", "else:\n", " # If we found matching directories\n", " print(f\"Found matching directories: {matching_dirs}\")\n", " \n", " # Select the most specific directory for rectal cancer\n", " if \"TCGA_Rectal_Cancer_(READ)\" in matching_dirs:\n", " selected_dir = \"TCGA_Rectal_Cancer_(READ)\" # Choose the most specific match\n", " else:\n", " selected_dir = matching_dirs[0] # Default to first match if specific one not found\n", " \n", " print(f\"Selected directory: {selected_dir}\")\n", " cohort_dir = os.path.join(tcga_root_dir, selected_dir)\n", " \n", " # Step 2: Get file paths for clinical and genetic data\n", " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", " \n", " # Step 3: Load the 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", " # Step 4: Print column names of clinical data\n", " print(\"Clinical data columns:\")\n", " print(clinical_df.columns.tolist())\n" ] }, { "cell_type": "markdown", "id": "e032b442", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "4de6f594", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:55.238055Z", "iopub.status.busy": "2025-03-25T03:47:55.237921Z", "iopub.status.idle": "2025-03-25T03:47:55.246014Z", "shell.execute_reply": "2025-03-25T03:47:55.245713Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [57.0, 41.0, 41.0, 76.0, 48.0], 'days_to_birth': [-21098.0, -15082.0, -15082.0, -28119.0, -17759.0]}\n", "\n", "Gender columns preview:\n", "{'gender': ['MALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Identify candidate columns for age and gender\n", "candidate_age_cols = [\"age_at_initial_pathologic_diagnosis\", \"days_to_birth\"]\n", "candidate_gender_cols = [\"gender\"]\n", "\n", "# Define cohort directory path\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Rectal_Cancer_(READ)\")\n", "\n", "# Get clinical file path\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Read the clinical data\n", "clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\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", "# 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(\"Age columns preview:\")\n", "print(age_preview)\n", "print(\"\\nGender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "c112f776", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "1744003a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:55.247131Z", "iopub.status.busy": "2025-03-25T03:47:55.247012Z", "iopub.status.idle": "2025-03-25T03:47:55.249705Z", "shell.execute_reply": "2025-03-25T03:47:55.249407Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Chosen age column: age_at_initial_pathologic_diagnosis\n", "First 5 values of age column: [57.0, 41.0, 41.0, 76.0, 48.0]\n", "Chosen gender column: gender\n", "First 5 values of gender column: ['MALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']\n" ] } ], "source": [ "# Evaluate age columns\n", "age_col_candidates = {'age_at_initial_pathologic_diagnosis': [57.0, 41.0, 41.0, 76.0, 48.0], \n", " 'days_to_birth': [-21098.0, -15082.0, -15082.0, -28119.0, -17759.0]}\n", "\n", "# Evaluate gender columns\n", "gender_col_candidates = {'gender': ['MALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']}\n", "\n", "# Select age column\n", "# 'age_at_initial_pathologic_diagnosis' provides direct age values, while 'days_to_birth' requires conversion\n", "# Both columns have no missing values in the preview, but 'age_at_initial_pathologic_diagnosis' is more straightforward\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# Select gender column\n", "# Only one gender column available which contains valid values\n", "gender_col = 'gender'\n", "\n", "# Print the chosen columns\n", "print(f\"Chosen age column: {age_col}\")\n", "print(f\"First 5 values of age column: {age_col_candidates[age_col]}\")\n", "print(f\"Chosen gender column: {gender_col}\")\n", "print(f\"First 5 values of gender column: {gender_col_candidates[gender_col]}\")\n" ] }, { "cell_type": "markdown", "id": "f5d34360", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "994c32a8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:47:55.250781Z", "iopub.status.busy": "2025-03-25T03:47:55.250677Z", "iopub.status.idle": "2025-03-25T03:48:09.567245Z", "shell.execute_reply": "2025-03-25T03:48:09.566721Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Saved clinical data with 186 samples\n", "After normalization: 19848 genes remaining\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene expression data\n", "Linked data shape: (105, 19851) (samples x features)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (105, 19851)\n", "For the feature 'Rectal_Cancer', the least common label is '0' with 10 occurrences. This represents 9.52% of the dataset.\n", "The distribution of the feature 'Rectal_Cancer' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 54.0\n", " 50% (Median): 63.0\n", " 75%: 73.0\n", "Min: 31.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.0' with 49 occurrences. This represents 46.67% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved usable linked data to ../../output/preprocess/Rectal_Cancer/TCGA.csv\n" ] } ], "source": [ "# Step 1: Extract and standardize clinical features\n", "# Use the Rectal Cancer directory identified in Step 1\n", "selected_dir = \"TCGA_Rectal_Cancer_(READ)\"\n", "cohort_dir = os.path.join(tcga_root_dir, selected_dir)\n", "\n", "# Get the file paths for clinical and genetic data\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Load the 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", "# Extract standardized clinical features using the provided trait variable\n", "clinical_features = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=trait, # Using the provided trait variable\n", " age_col=age_col, \n", " gender_col=gender_col\n", ")\n", "\n", "# Save the clinical data to out_clinical_data_file\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\"Saved clinical data with {len(clinical_features)} samples\")\n", "\n", "# Step 2: Normalize gene symbols in gene expression data\n", "# Transpose to get genes as rows\n", "gene_df = genetic_df\n", "\n", "# Normalize gene symbols using NCBI Gene database synonyms\n", "normalized_gene_df = normalize_gene_symbols_in_index(gene_df)\n", "print(f\"After normalization: {len(normalized_gene_df)} genes remaining\")\n", "\n", "# Save the normalized gene expression 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\"Saved normalized gene expression data\")\n", "\n", "# Step 3: Link clinical and genetic data\n", "# Merge clinical features with genetic expression data\n", "linked_data = clinical_features.join(normalized_gene_df.T, how='inner')\n", "print(f\"Linked data shape: {linked_data.shape} (samples x features)\")\n", "\n", "# Step 4: Handle missing values\n", "cleaned_data = handle_missing_values(linked_data, trait_col=trait)\n", "print(f\"After handling missing values, data shape: {cleaned_data.shape}\")\n", "\n", "# Step 5: Determine if trait or demographics are severely biased\n", "trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait=trait)\n", "\n", "# Step 6: Validate data quality and save cohort information\n", "note = \"The dataset contains gene expression data along with clinical information for rectal cancer patients from TCGA.\"\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=cleaned_data,\n", " note=note\n", ")\n", "\n", "# Step 7: Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Saved usable linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset was determined to be unusable and was not 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 }