{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "d9c9c2e2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:47.483462Z", "iopub.status.busy": "2025-03-25T04:09:47.483247Z", "iopub.status.idle": "2025-03-25T04:09:47.676330Z", "shell.execute_reply": "2025-03-25T04:09:47.675971Z" } }, "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 = \"Thymoma\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Thymoma/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Thymoma/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Thymoma/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Thymoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "cc812df0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e545c686", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:47.677798Z", "iopub.status.busy": "2025-03-25T04:09:47.677652Z", "iopub.status.idle": "2025-03-25T04:09:48.019811Z", "shell.execute_reply": "2025-03-25T04:09:48.019407Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Available TCGA directories:\n", "['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" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Clinical data columns:\n", "['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_after_initial_treatment', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_myasthenia_gravis', 'history_of_neoadjuvant_treatment', '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', 'lost_follow_up', 'masaoka_stage', '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', 'oct_embedded', 'other_dx', 'pathology_report_file_name', 'patient_id', 'person_neoplasm_cancer_status', 'post_op_ablation_embolization_tx', 'postoperative_rx_tx', 'radiation_therapy', 'sample_type', 'sample_type_id', 'section_myasthenia_gravis', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_THYM_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_THYM_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_THYM_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_THYM_exp_HiSeqV2', '_GENOMIC_ID_TCGA_THYM_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_THYM_hMethyl450', '_GENOMIC_ID_TCGA_THYM_gistic2', '_GENOMIC_ID_TCGA_THYM_gistic2thd', '_GENOMIC_ID_data/public/TCGA/THYM/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_THYM_mutation_bcm_gene', '_GENOMIC_ID_TCGA_THYM_miRNA_HiSeq', '_GENOMIC_ID_TCGA_THYM_mutation_broad_gene', '_GENOMIC_ID_TCGA_THYM_PDMRNAseq', '_GENOMIC_ID_TCGA_THYM_RPPA', '_GENOMIC_ID_TCGA_THYM_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_THYM_mutation_bcgsc_gene']\n", "\n", "Clinical data shape: (126, 73)\n", "Genetic data shape: (20530, 122)\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# Review subdirectories to find the most relevant match for Mesothelioma\n", "all_dirs = os.listdir(tcga_root_dir)\n", "\n", "# Print all available directories for debugging\n", "print(\"Available TCGA directories:\")\n", "print(all_dirs)\n", "\n", "# Looking for directories related to our target trait\n", "trait_related_dirs = [d for d in all_dirs if trait.lower() in d.lower()]\n", "\n", "if len(trait_related_dirs) > 0:\n", " # If we found related directories, choose the most specific one\n", " selected_dir = trait_related_dirs[0]\n", " selected_path = os.path.join(tcga_root_dir, selected_dir)\n", " \n", " # Get paths to the clinical and genetic data files\n", " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(selected_path)\n", " \n", " # Load the data files\n", " clinical_data = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n", " genetic_data = pd.read_csv(genetic_file_path, index_col=0, sep='\\t')\n", " \n", " # Print the column names of the clinical data\n", " print(\"Clinical data columns:\")\n", " print(clinical_data.columns.tolist())\n", " \n", " # Also print basic information about both datasets\n", " print(\"\\nClinical data shape:\", clinical_data.shape)\n", " print(\"Genetic data shape:\", genetic_data.shape)\n", " \n", " # Set flags for validation\n", " is_gene_available = genetic_data.shape[0] > 0\n", " is_trait_available = clinical_data.shape[0] > 0\n", "else:\n", " print(f\"No directories found related to {trait} in the TCGA dataset.\")\n", " \n", " # Mark this task as completed with no suitable directory found\n", " is_gene_available = False\n", " is_trait_available = False\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" ] }, { "cell_type": "markdown", "id": "c5458cda", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "152461d7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:48.021069Z", "iopub.status.busy": "2025-03-25T04:09:48.020936Z", "iopub.status.idle": "2025-03-25T04:09:48.027713Z", "shell.execute_reply": "2025-03-25T04:09:48.027391Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Candidate age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [47.0, 66.0, 45.0, 51.0, 76.0], 'days_to_birth': [-17528.0, -24460.0, -16728.0, -18733.0, -27827.0]}\n", "\n", "Candidate gender columns preview:\n", "{'gender': ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']}\n" ] } ], "source": [ "# 1. Identify candidate demographic columns\n", "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n", "candidate_gender_cols = ['gender']\n", "\n", "# 2. Load the clinical data to preview the candidate columns\n", "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Thymoma_(THYM)')\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 candidate 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", "# Extract and preview candidate 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(\"Candidate age columns preview:\")\n", "print(age_preview)\n", "print(\"\\nCandidate gender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "1adb1b26", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "da73f211", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:48.028762Z", "iopub.status.busy": "2025-03-25T04:09:48.028656Z", "iopub.status.idle": "2025-03-25T04:09:48.032228Z", "shell.execute_reply": "2025-03-25T04:09:48.031903Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# Selecting the appropriate demographic columns\n", "age_col = None\n", "gender_col = None\n", "\n", "# Examining age columns\n", "age_cols_dict = {'age_at_initial_pathologic_diagnosis': [47.0, 66.0, 45.0, 51.0, 76.0], \n", " 'days_to_birth': [-17528.0, -24460.0, -16728.0, -18733.0, -27827.0]}\n", "\n", "if age_cols_dict:\n", " # Prefer 'age_at_initial_pathologic_diagnosis' as it's already in years and more interpretable\n", " if 'age_at_initial_pathologic_diagnosis' in age_cols_dict and not all(pd.isna(v) for v in age_cols_dict['age_at_initial_pathologic_diagnosis']):\n", " age_col = 'age_at_initial_pathologic_diagnosis'\n", " # If not available, use 'days_to_birth' (negative values representing days before study entry)\n", " elif 'days_to_birth' in age_cols_dict and not all(pd.isna(v) for v in age_cols_dict['days_to_birth']):\n", " age_col = 'days_to_birth'\n", "\n", "# Examining gender columns\n", "gender_cols_dict = {'gender': ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']}\n", "\n", "if gender_cols_dict:\n", " # Check if 'gender' column exists with valid values\n", " if 'gender' in gender_cols_dict and not all(pd.isna(v) for v in gender_cols_dict['gender']):\n", " gender_col = 'gender'\n", "\n", "# Print the selected columns\n", "print(f\"Selected age column: {age_col}\")\n", "print(f\"Selected gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "326c938a", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "d0396c4c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:48.033268Z", "iopub.status.busy": "2025-03-25T04:09:48.033169Z", "iopub.status.idle": "2025-03-25T04:09:56.207345Z", "shell.execute_reply": "2025-03-25T04:09:56.207017Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Thymoma/gene_data/TCGA.csv\n", "Gene data shape after normalization: (19848, 122)\n", "Linked data shape: (122, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (122, 19851)\n", "For the feature 'Thymoma', the least common label is '0' with 2 occurrences. This represents 1.64% of the dataset.\n", "The distribution of the feature 'Thymoma' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 48.0\n", " 50% (Median): 58.5\n", " 75%: 68.0\n", "Min: 17.0\n", "Max: 84.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' with 59 occurrences. This represents 48.36% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Dataset not usable for analysis. Data not saved.\n" ] } ], "source": [ "# Look for the directory related to Thymoma trait\n", "thymoma_dir = [d for d in os.listdir(tcga_root_dir) if \"thym\" in d.lower()][0]\n", "selected_path = os.path.join(tcga_root_dir, thymoma_dir)\n", "\n", "# Reload the clinical and genetic data files\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(selected_path)\n", "clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n", "genetic_df = pd.read_csv(genetic_file_path, index_col=0, sep='\\t')\n", "\n", "# 1. Extract and standardize clinical features (trait, age, gender)\n", "selected_clinical_df = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=trait, \n", " age_col=age_col, \n", " gender_col=gender_col\n", ")\n", "\n", "# 2. Normalize gene symbols in gene expression data\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 data saved to {out_gene_data_file}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_df.shape}\")\n", "\n", "# 3. Link clinical and genetic data\n", "# Transpose the genetic data to have samples as rows\n", "genetic_df_t = normalized_gene_df.T\n", "# Ensure the indices match between datasets\n", "common_samples = list(set(genetic_df_t.index) & set(selected_clinical_df.index))\n", "genetic_df_filtered = genetic_df_t.loc[common_samples]\n", "clinical_df_filtered = selected_clinical_df.loc[common_samples]\n", "\n", "# Combine the datasets\n", "linked_data = pd.concat([clinical_df_filtered, genetic_df_filtered], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data_cleaned = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Determine if trait and demographic features are biased\n", "is_biased, linked_data_filtered = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", "\n", "# 6. Validate data quality and save cohort information\n", "# First check if gene and trait data are available\n", "is_gene_available = linked_data_filtered.shape[1] > 3 # More columns than just trait, age, gender\n", "is_trait_available = trait in linked_data_filtered.columns\n", "\n", "# Second validation for saving metadata\n", "note = f\"Dataset contains {linked_data_filtered.shape[0]} samples and {linked_data_filtered.shape[1] - 3} genes after preprocessing.\"\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data_filtered,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_filtered.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " \n", " # Also save the clinical data separately\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_cols = [col for col in linked_data_filtered.columns if col in [trait, 'Age', 'Gender']]\n", " linked_data_filtered[clinical_cols].to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"Dataset not usable for analysis. Data 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 }