{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "aafb97b5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:58.914967Z", "iopub.status.busy": "2025-03-25T07:18:58.914729Z", "iopub.status.idle": "2025-03-25T07:18:59.082539Z", "shell.execute_reply": "2025-03-25T07:18:59.082095Z" } }, "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 = \"Kidney_Clear_Cell_Carcinoma\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Kidney_Clear_Cell_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "7dc8c6bd", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "514c54bc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:59.083946Z", "iopub.status.busy": "2025-03-25T07:18:59.083801Z", "iopub.status.idle": "2025-03-25T07:18:59.329634Z", "shell.execute_reply": "2025-03-25T07:18:59.328973Z" } }, "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 match: TCGA_Kidney_Chromophobe_(KICH)\n", "Selected directory: TCGA_Kidney_Chromophobe_(KICH)\n", "Clinical file: TCGA.KICH.sampleMap_KICH_clinicalMatrix\n", "Genetic file: TCGA.KICH.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_surgery_locoregional_procedure', 'additional_surgery_metastatic_procedure', 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'clinical_M', 'days_to_additional_surgery_metastatic_procedure', 'days_to_birth', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_after_initial_treatment', 'eastern_cancer_oncology_group', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'hemoglobin_result', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'intermediate_dimension', 'is_ffpe', 'karnofsky_performance_score', 'lactate_dehydrogenase_result', 'laterality', 'longest_dimension', 'lost_follow_up', 'lymph_node_examined_count', 'new_tumor_event_after_initial_treatment', 'number_of_lymphnodes_positive', 'number_pack_years_smoked', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'percent_tumor_sarcomatoid', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'platelet_qualitative_result', 'presence_of_sarcomatoid_features', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'radiation_therapy', 'sample_type', 'sample_type_id', 'serum_calcium_result', 'shortest_dimension', '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', 'white_cell_count_result', 'year_of_initial_pathologic_diagnosis', 'year_of_tobacco_smoking_onset', '_GENOMIC_ID_TCGA_KICH_PDMRNAseq', '_GENOMIC_ID_TCGA_KICH_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_KICH_gistic2thd', '_GENOMIC_ID_TCGA_KICH_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_KICH_exp_HiSeqV2', '_GENOMIC_ID_TCGA_KICH_RPPA', '_GENOMIC_ID_TCGA_KICH_miRNA_HiSeq', '_GENOMIC_ID_TCGA_KICH_mutation_bcm_gene', '_GENOMIC_ID_TCGA_KICH_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_KICH_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_KICH_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_KICH_hMethyl450', '_GENOMIC_ID_TCGA_KICH_mutation_broad_gene', '_GENOMIC_ID_data/public/TCGA/KICH/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_KICH_gistic2']\n", "\n", "Clinical data shape: (91, 90)\n", "Genetic data shape: (20530, 91)\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 Kidney_Chromophobe\n", "# Convert trait to lowercase for case-insensitive matching\n", "target_trait = trait.lower() # \"kidney_chromophobe\"\n", "\n", "# Search for the exact directory matching our trait\n", "best_match = None\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 if the directory name contains our trait\n", " if target_trait in subdir_lower or 'kich' in subdir_lower: # KICH is the TCGA code for Kidney Chromophobe\n", " best_match = subdir\n", " print(f\"Found match: {subdir}\")\n", " break\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": "ca69ce9e", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "ffedb50e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:59.331524Z", "iopub.status.busy": "2025-03-25T07:18:59.331393Z", "iopub.status.idle": "2025-03-25T07:18:59.356398Z", "shell.execute_reply": "2025-03-25T07:18:59.355906Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Candidate age columns:\n", "['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n", "\n", "Age data preview:\n", "{'age_at_initial_pathologic_diagnosis': [69, 68, 67, 67, 66], 'days_to_birth': [-25205.0, -25043.0, -24569.0, -24569.0, -24315.0]}\n", "\n", "Candidate gender columns:\n", "['gender']\n", "\n", "Gender data preview:\n", "{'gender': ['MALE', 'FEMALE', 'MALE', 'MALE', 'MALE']}\n" ] } ], "source": [ "# Check which columns are likely to contain age information\n", "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n", "candidate_gender_cols = ['gender']\n", "\n", "# Load the clinical data file\n", "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)')\n", "clinical_file_path, genetic_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 the candidate 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", "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(\"Candidate age columns:\")\n", "print(candidate_age_cols)\n", "print(\"\\nAge data preview:\")\n", "print(age_preview)\n", "\n", "print(\"\\nCandidate gender columns:\")\n", "print(candidate_gender_cols)\n", "print(\"\\nGender data preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "cfc9181f", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "f895f178", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:59.358188Z", "iopub.status.busy": "2025-03-25T07:18:59.358067Z", "iopub.status.idle": "2025-03-25T07:18:59.361482Z", "shell.execute_reply": "2025-03-25T07:18:59.361018Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Age data preview: [69, 68, 67, 67, 66]\n", "Selected gender column: gender\n", "Gender data preview: ['MALE', 'FEMALE', 'MALE', 'MALE', 'MALE']\n" ] } ], "source": [ "# Analyze the age columns\n", "age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n", "age_data = {'age_at_initial_pathologic_diagnosis': [69, 68, 67, 67, 66], \n", " 'days_to_birth': [-25205.0, -25043.0, -24569.0, -24569.0, -24315.0]}\n", "\n", "# Analyze the gender columns\n", "gender_cols = ['gender']\n", "gender_data = {'gender': ['MALE', 'FEMALE', 'MALE', 'MALE', 'MALE']}\n", "\n", "# Select age column\n", "# Both columns have valid data, but age_at_initial_pathologic_diagnosis is already in years format,\n", "# while days_to_birth would need conversion (negative days from birth)\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# Select gender column\n", "# Only one column is available and it contains valid gender information\n", "gender_col = 'gender'\n", "\n", "# Print the chosen columns\n", "print(f\"Selected age column: {age_col}\")\n", "print(f\"Age data preview: {age_data[age_col]}\")\n", "print(f\"Selected gender column: {gender_col}\")\n", "print(f\"Gender data preview: {gender_data[gender_col]}\")\n" ] }, { "cell_type": "markdown", "id": "edd46210", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "a8e40af4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:18:59.363255Z", "iopub.status.busy": "2025-03-25T07:18:59.363141Z", "iopub.status.idle": "2025-03-25T07:19:00.754399Z", "shell.execute_reply": "2025-03-25T07:19:00.753758Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/gene_data/TCGA.csv\n", "Gene expression data shape after normalization: (19848, 91)\n", "Clinical data saved to ../../output/preprocess/Kidney_Clear_Cell_Carcinoma/clinical_data/TCGA.csv\n", "Clinical data shape: (945, 3)\n", "Number of samples in clinical data: 945\n", "Number of samples in genetic data: 91\n", "Number of common samples: 0\n", "Linked data shape: (0, 19851)\n", "Data shape after handling missing values: (0, 2)\n", "Quartiles for 'Kidney_Clear_Cell_Carcinoma':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Kidney_Clear_Cell_Carcinoma' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "Abnormality detected in the cohort: TCGA. Preprocessing failed.\n", "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 }