{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "d2157d12", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:00:29.598440Z", "iopub.status.busy": "2025-03-25T08:00:29.598202Z", "iopub.status.idle": "2025-03-25T08:00:29.770081Z", "shell.execute_reply": "2025-03-25T08:00:29.769642Z" } }, "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 = \"Mesothelioma\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mesothelioma/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mesothelioma/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mesothelioma/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Mesothelioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "1ae3493d", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "b6d15e6e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:00:29.771487Z", "iopub.status.busy": "2025-03-25T08:00:29.771351Z", "iopub.status.idle": "2025-03-25T08:00:30.019679Z", "shell.execute_reply": "2025-03-25T08:00:30.019212Z" } }, "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', 'asbestos_exposure_age', 'asbestos_exposure_age_last', 'asbestos_exposure_source', 'asbestos_exposure_type', 'asbestos_exposure_years', 'assessment_timepoint_category', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'creatinine_norm_range_lower', 'creatinine_norm_range_upper', 'creatinine_prior_tx', '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', 'eastern_cancer_oncology_group', 'family_history_cancer_type', 'family_history_cancer_type_other', 'family_member_relationship_type', 'form_completion_date', 'gender', 'histological_type', 'history_asbestos_exposure', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'is_ffpe', 'karnofsky_performance_score', 'laterality', 'lost_follow_up', 'mesothelioma_detection_method', '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', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'person_occupation_years_number', 'pleurodesis_performed', 'pleurodesis_performed_90_days', 'postoperative_rx_tx', 'primary_occupation', 'primary_occupation_other', 'radiation_therapy', 'residual_tumor', 'sample_type', 'sample_type_id', 'serum_mesothelin_lower_limit', 'serum_mesothelin_prior_tx', 'serum_mesothelin_upper_limit', 'suv_of_pleura_max', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_MESO_PDMRNAseq', '_GENOMIC_ID_data/public/TCGA/MESO/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_MESO_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_MESO_mutation_broad_gene', '_GENOMIC_ID_TCGA_MESO_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_MESO_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_MESO_RPPA', '_GENOMIC_ID_TCGA_MESO_gistic2', '_GENOMIC_ID_TCGA_MESO_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_MESO_miRNA_HiSeq', '_GENOMIC_ID_TCGA_MESO_exp_HiSeqV2', '_GENOMIC_ID_TCGA_MESO_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_MESO_gistic2thd', '_GENOMIC_ID_TCGA_MESO_hMethyl450']\n", "\n", "Clinical data shape: (87, 96)\n", "Genetic data shape: (20530, 87)\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": "3b93f2c3", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "2d8cdfba", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:00:30.021163Z", "iopub.status.busy": "2025-03-25T08:00:30.021036Z", "iopub.status.idle": "2025-03-25T08:00:30.029096Z", "shell.execute_reply": "2025-03-25T08:00:30.028721Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Candidate age columns:\n", "['age_at_initial_pathologic_diagnosis', 'asbestos_exposure_age', 'asbestos_exposure_age_last', 'days_to_birth']\n", "\n", "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [64, 60, 53, 58, 69], 'asbestos_exposure_age': [nan, nan, nan, 25.0, nan], 'asbestos_exposure_age_last': [nan, nan, nan, 31.0, nan], 'days_to_birth': [-23591, -21972, -19503, -21423, -25471]}\n", "\n", "Candidate gender columns:\n", "['gender']\n", "\n", "Gender columns preview:\n", "{'gender': ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']}\n" ] } ], "source": [ "# Identify potential age-related columns\n", "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'asbestos_exposure_age', \n", " 'asbestos_exposure_age_last', 'days_to_birth']\n", "\n", "# Identify potential gender-related columns\n", "candidate_gender_cols = ['gender']\n", "\n", "# Let's first load the data for the cohort\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Mesothelioma_(MESO)\")\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Try reading the file with tab delimiter which is common in TCGA files\n", "try:\n", " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n", "except Exception as e:\n", " print(f\"Error with tab delimiter: {e}\")\n", " # If that fails, try the python engine which can detect the delimiter\n", " try:\n", " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep=None, engine='python')\n", " except Exception as e:\n", " print(f\"Error with python engine: {e}\")\n", " # As a last resort, try various common delimiters\n", " for sep in [',', ';', '|']:\n", " try:\n", " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep=sep)\n", " print(f\"Successfully read with delimiter: '{sep}'\")\n", " break\n", " except:\n", " continue\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", "# Display the previews\n", "print(\"Candidate age columns:\")\n", "print(candidate_age_cols)\n", "print(\"\\nAge columns preview:\")\n", "print(age_preview)\n", "\n", "print(\"\\nCandidate gender columns:\")\n", "print(candidate_gender_cols)\n", "print(\"\\nGender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "7117c78d", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "c8b96798", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:00:30.030303Z", "iopub.status.busy": "2025-03-25T08:00:30.030189Z", "iopub.status.idle": "2025-03-25T08:00:30.032561Z", "shell.execute_reply": "2025-03-25T08:00:30.032205Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# Examine the candidate age columns\n", "# age_at_initial_pathologic_diagnosis: Contains actual ages (seems most direct)\n", "# asbestos_exposure_age and asbestos_exposure_age_last: Many NaN values\n", "# days_to_birth: Contains negative values (days before birth, would need conversion)\n", "\n", "# Examine the candidate gender column\n", "# gender: Contains clear MALE/FEMALE values\n", "\n", "# Select the appropriate columns\n", "age_col = \"age_at_initial_pathologic_diagnosis\" # Most direct representation of patient age\n", "gender_col = \"gender\" # Only candidate and contains proper values\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": "e238d767", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "bb57be59", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:00:30.033742Z", "iopub.status.busy": "2025-03-25T08:00:30.033634Z", "iopub.status.idle": "2025-03-25T08:00:37.206647Z", "shell.execute_reply": "2025-03-25T08:00:37.206314Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Mesothelioma/gene_data/TCGA.csv\n", "Gene data shape after normalization: (19848, 87)\n", "Linked data shape: (87, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (87, 19851)\n", "Quartiles for 'Mesothelioma':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1\n", "Max: 1\n", "The distribution of the feature 'Mesothelioma' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 57.0\n", " 50% (Median): 64.0\n", " 75%: 69.0\n", "Min: 28\n", "Max: 81\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 16 occurrences. This represents 18.39% 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": [ "# Let's use the correct folder for Mesothelioma data\n", "selected_dir = \"TCGA_Mesothelioma_(MESO)\"\n", "selected_path = os.path.join(tcga_root_dir, selected_dir)\n", "\n", "# Reload the clinical and genetic data files to ensure we're using the correct dataset\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 }