{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "1c558516", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:24:34.027298Z", "iopub.status.busy": "2025-03-25T08:24:34.027192Z", "iopub.status.idle": "2025-03-25T08:24:34.191533Z", "shell.execute_reply": "2025-03-25T08:24:34.191191Z" } }, "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 = \"Colon_and_Rectal_Cancer\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Colon_and_Rectal_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3d3e1f61", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e1bc4a32", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:24:34.192902Z", "iopub.status.busy": "2025-03-25T08:24:34.192764Z", "iopub.status.idle": "2025-03-25T08:24:35.172682Z", "shell.execute_reply": "2025-03-25T08:24:35.172316Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found potential match: TCGA_Liver_Cancer_(LIHC) (score: 1)\n", "Found potential match: TCGA_Rectal_Cancer_(READ) (score: 2)\n", "Found potential match: TCGA_Colon_and_Rectal_Cancer_(COADREAD) (score: 4)\n", "Selected directory: TCGA_Colon_and_Rectal_Cancer_(COADREAD)\n", "Clinical file: TCGA.COADREAD.sampleMap_COADREAD_clinicalMatrix\n", "Genetic file: TCGA.COADREAD.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "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_COADREAD', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_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', 'disease_code', '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', 'project_code', '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_COADREAD_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_COADREAD_PDMRNAseq', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_COADREAD_hMethyl450', '_GENOMIC_ID_TCGA_COADREAD_gistic2thd', '_GENOMIC_ID_TCGA_COADREAD_hMethyl27', '_GENOMIC_ID_TCGA_COADREAD_G4502A_07_3', '_GENOMIC_ID_TCGA_COADREAD_PDMarrayCNV', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2', '_GENOMIC_ID_TCGA_COADREAD_PDMarray', '_GENOMIC_ID_TCGA_COADREAD_gistic2', '_GENOMIC_ID_TCGA_COADREAD_mutation', '_GENOMIC_ID_TCGA_COADREAD_RPPA_RBN', '_GENOMIC_ID_TCGA_COADREAD_PDMRNAseqCNV']\n", "\n", "Clinical data shape: (736, 123)\n", "Genetic data shape: (20530, 434)\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# 1. Find the most relevant directory for Colon and Rectal Cancer\n", "subdirectories = os.listdir(tcga_root_dir)\n", "target_trait = trait.lower().replace(\"_\", \" \") # Convert to lowercase for case-insensitive matching\n", "\n", "# Start with no match, then find the best match based on similarity to target trait\n", "best_match = None\n", "best_match_score = 0\n", "\n", "for subdir in subdirectories:\n", " subdir_lower = subdir.lower()\n", " \n", " # Calculate a simple similarity score - more matching words = better match\n", " # This prioritizes exact matches over partial matches\n", " score = 0\n", " for word in target_trait.split():\n", " if word in subdir_lower:\n", " score += 1\n", " \n", " # Track the best match\n", " if score > best_match_score:\n", " best_match_score = score\n", " best_match = subdir\n", " print(f\"Found potential match: {subdir} (score: {score})\")\n", "\n", "# Use the best match if 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.\")\n" ] }, { "cell_type": "markdown", "id": "709cd3d3", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "5933e2a7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:24:35.174114Z", "iopub.status.busy": "2025-03-25T08:24:35.174008Z", "iopub.status.idle": "2025-03-25T08:24:35.185666Z", "shell.execute_reply": "2025-03-25T08:24:35.185376Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [61.0, 67.0, 42.0, 74.0, nan], 'days_to_birth': [-22379.0, -24523.0, -15494.0, -27095.0, nan]}\n", "\n", "Gender columns preview:\n", "{'gender': ['FEMALE', 'MALE', 'FEMALE', 'MALE', nan]}\n" ] } ], "source": [ "# Identify columns that might contain age information\n", "candidate_age_cols = [\n", " 'age_at_initial_pathologic_diagnosis',\n", " 'days_to_birth' # Negative days to birth can represent age\n", "]\n", "\n", "# Identify columns that might contain gender information\n", "candidate_gender_cols = [\n", " 'gender'\n", "]\n", "\n", "# Load the clinical data to examine these columns\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Colon_and_Rectal_Cancer_(COADREAD)\")\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Extract and preview age-related columns\n", "if candidate_age_cols:\n", " age_df = clinical_df[candidate_age_cols]\n", " print(\"Age columns preview:\")\n", " print(preview_df(age_df))\n", "\n", "# Extract and preview gender-related columns\n", "if candidate_gender_cols:\n", " gender_df = clinical_df[candidate_gender_cols]\n", " print(\"\\nGender columns preview:\")\n", " print(preview_df(gender_df))\n" ] }, { "cell_type": "markdown", "id": "37d99797", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "88b72458", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:24:35.186985Z", "iopub.status.busy": "2025-03-25T08:24:35.186885Z", "iopub.status.idle": "2025-03-25T08:24:35.190161Z", "shell.execute_reply": "2025-03-25T08:24:35.189875Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age column candidates:\n", "Column: age_at_initial_pathologic_diagnosis, Values: [61.0, 67.0, 42.0, 74.0, None], Missing: 20.0%\n", "Column: days_to_birth, Values: [-22379.0, -24523.0, -15494.0, -27095.0, None], Missing: 20.0%\n", "\n", "Gender column candidates:\n", "Column: gender, Values: ['FEMALE', 'MALE', 'FEMALE', 'MALE', None], Missing: 20.0%\n", "\n", "Selected columns:\n", "Age column: age_at_initial_pathologic_diagnosis\n", "Gender column: gender\n" ] } ], "source": [ "# Check the age columns\n", "print(\"Age column candidates:\")\n", "for col, values in {'age_at_initial_pathologic_diagnosis': [61.0, 67.0, 42.0, 74.0, None], \n", " 'days_to_birth': [-22379.0, -24523.0, -15494.0, -27095.0, None]}.items():\n", " missing_count = sum(1 for v in values if v is None or pd.isna(v))\n", " missing_percentage = missing_count / len(values) * 100\n", " print(f\"Column: {col}, Values: {values}, Missing: {missing_percentage:.1f}%\")\n", "\n", "# Check the gender columns\n", "print(\"\\nGender column candidates:\")\n", "for col, values in {'gender': ['FEMALE', 'MALE', 'FEMALE', 'MALE', None]}.items():\n", " missing_count = sum(1 for v in values if v is None or pd.isna(v))\n", " missing_percentage = missing_count / len(values) * 100\n", " print(f\"Column: {col}, Values: {values}, Missing: {missing_percentage:.1f}%\")\n", "\n", "# Select the columns\n", "age_col = 'age_at_initial_pathologic_diagnosis' # Clear age values in years\n", "gender_col = 'gender' # Standard gender labels\n", "\n", "print(\"\\nSelected columns:\")\n", "print(f\"Age column: {age_col}\")\n", "print(f\"Gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "a3d7c8f6", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "342d196e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:24:35.191386Z", "iopub.status.busy": "2025-03-25T08:24:35.191287Z", "iopub.status.idle": "2025-03-25T08:25:13.819637Z", "shell.execute_reply": "2025-03-25T08:25:13.818967Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/gene_data/TCGA.csv\n", "Gene expression data shape after normalization: (19848, 434)\n", "Clinical data saved to ../../output/preprocess/Colon_and_Rectal_Cancer/clinical_data/TCGA.csv\n", "Clinical data shape: (736, 3)\n", "Number of samples in clinical data: 736\n", "Number of samples in genetic data: 434\n", "Number of common samples: 434\n", "Linked data shape: (434, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (434, 19851)\n", "For the feature 'Colon_and_Rectal_Cancer', the least common label is '0' with 51 occurrences. This represents 11.75% of the dataset.\n", "The distribution of the feature 'Colon_and_Rectal_Cancer' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 56.0\n", " 50% (Median): 66.0\n", " 75%: 75.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 199 occurrences. This represents 45.85% 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/Colon_and_Rectal_Cancer/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 }