{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "88e47a8e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:00.280904Z", "iopub.status.busy": "2025-03-25T07:57:00.280674Z", "iopub.status.idle": "2025-03-25T07:57:00.445559Z", "shell.execute_reply": "2025-03-25T07:57:00.445228Z" } }, "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 = \"Melanoma\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Melanoma/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Melanoma/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Melanoma/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Melanoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3a68c479", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "bda0d92c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:00.447003Z", "iopub.status.busy": "2025-03-25T07:57:00.446861Z", "iopub.status.idle": "2025-03-25T07:57:01.573492Z", "shell.execute_reply": "2025-03-25T07:57:01.573114Z" } }, "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', 'breslow_depth_value', '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', 'days_to_submitted_specimen_dx', 'distant_metastasis_anatomic_site', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'interferon_90_day_prior_excision_admin_indicator', 'is_ffpe', 'lactate_dehydrogenase_result', 'lost_follow_up', 'malignant_neoplasm_mitotic_count_rate', 'melanoma_clark_level_value', 'melanoma_origin_skin_anatomic_site', 'melanoma_ulceration_indicator', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_non_melanoma_event_histologic_type_text', 'new_primary_melanoma_anatomic_site', 'new_tumor_dx_prior_submitted_specimen_dx', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'new_tumor_metastasis_anatomic_site', 'new_tumor_metastasis_anatomic_site_other_text', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'primary_anatomic_site_count', 'primary_melanoma_at_diagnosis_count', 'primary_neoplasm_melanoma_dx', 'primary_tumor_multiple_present_ind', 'prior_systemic_therapy_type', 'radiation_therapy', 'sample_type', 'sample_type_id', 'subsequent_primary_melanoma_during_followup', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tissue_type', 'tumor_descriptor', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_SKCM_exp_HiSeqV2', '_GENOMIC_ID_TCGA_SKCM_hMethyl450', '_GENOMIC_ID_TCGA_SKCM_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_SKCM_miRNA_HiSeq', '_GENOMIC_ID_TCGA_SKCM_gistic2thd', '_GENOMIC_ID_data/public/TCGA/SKCM/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_SKCM_RPPA', '_GENOMIC_ID_TCGA_SKCM_mutation_bcm_gene', '_GENOMIC_ID_TCGA_SKCM_mutation_broad_gene', '_GENOMIC_ID_TCGA_SKCM_gistic2', '_GENOMIC_ID_TCGA_SKCM_mutation', '_GENOMIC_ID_TCGA_SKCM_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_SKCM_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_SKCM_PDMRNAseq', '_GENOMIC_ID_TCGA_SKCM_exp_HiSeqV2_percentile']\n", "\n", "Clinical data shape: (481, 93)\n", "Genetic data shape: (20530, 474)\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# Review subdirectories to find the most relevant match for Melanoma\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 Melanoma\n", "melanoma_related_dirs = [d for d in all_dirs if \"melanoma\" in d.lower()]\n", "\n", "if len(melanoma_related_dirs) > 0:\n", " # If we found related directories, choose the most specific one\n", " # Between 'TCGA_Melanoma_(SKCM)' and 'TCGA_Ocular_melanomas_(UVM)', SKCM is more representative of melanoma in general\n", " if \"TCGA_Melanoma_(SKCM)\" in melanoma_related_dirs:\n", " selected_dir = \"TCGA_Melanoma_(SKCM)\"\n", " else:\n", " selected_dir = melanoma_related_dirs[0]\n", " \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(\"No directories found related to Melanoma 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": "ad075dc4", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "424156fe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:01.574714Z", "iopub.status.busy": "2025-03-25T07:57:01.574605Z", "iopub.status.idle": "2025-03-25T07:57:01.583787Z", "shell.execute_reply": "2025-03-25T07:57:01.583505Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [71.0, 82.0, 82.0, 46.0, 74.0], 'days_to_birth': [-26176.0, -30286.0, -30163.0, -17025.0, -27124.0]}\n", "\n", "Gender columns preview:\n", "{'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Identify possible age and gender columns from clinical data\n", "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n", "candidate_gender_cols = ['gender']\n", "\n", "# Prepare to display the data\n", "import pandas as pd\n", "import os\n", "\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Melanoma_(SKCM)\")\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n", "\n", "# Preview age columns\n", "if candidate_age_cols:\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", " print(\"Age columns preview:\")\n", " print(age_preview)\n", "\n", "# Preview gender columns\n", "if candidate_gender_cols:\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", " print(\"\\nGender columns preview:\")\n", " print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "da294446", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "3d4ceec3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:01.584849Z", "iopub.status.busy": "2025-03-25T07:57:01.584748Z", "iopub.status.idle": "2025-03-25T07:57:01.587286Z", "shell.execute_reply": "2025-03-25T07:57:01.587012Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# Review age column candidates\n", "age_candidates = {\n", " 'age_at_initial_pathologic_diagnosis': [71.0, 82.0, 82.0, 46.0, 74.0], \n", " 'days_to_birth': [-26176.0, -30286.0, -30163.0, -17025.0, -27124.0]\n", "}\n", "\n", "# Review gender column candidates\n", "gender_candidates = {\n", " 'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']\n", "}\n", "\n", "# Select the appropriate columns\n", "# For age, 'age_at_initial_pathologic_diagnosis' is directly in years and easier to interpret\n", "age_col = 'age_at_initial_pathologic_diagnosis' if 'age_at_initial_pathologic_diagnosis' in age_candidates else None\n", "\n", "# For gender, there's only one candidate column and it contains valid values\n", "gender_col = 'gender' if 'gender' in gender_candidates else None\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": "3ed3de5b", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "51af74f9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:01.588325Z", "iopub.status.busy": "2025-03-25T07:57:01.588227Z", "iopub.status.idle": "2025-03-25T07:57:15.069953Z", "shell.execute_reply": "2025-03-25T07:57:15.069328Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Melanoma/gene_data/TCGA.csv\n", "Gene data shape after normalization: (19848, 474)\n", "Linked data shape: (474, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (474, 19851)\n", "For the feature 'Melanoma', the least common label is '0' with 1 occurrences. This represents 0.21% of the dataset.\n", "The distribution of the feature 'Melanoma' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 48.0\n", " 50% (Median): 58.0\n", " 75%: 70.75\n", "Min: 15.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 180 occurrences. This represents 37.97% 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 Melanoma data\n", "selected_dir = \"TCGA_Melanoma_(SKCM)\"\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 }