{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "805cd7fb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:30:14.231505Z", "iopub.status.busy": "2025-03-25T06:30:14.230938Z", "iopub.status.idle": "2025-03-25T06:30:14.401715Z", "shell.execute_reply": "2025-03-25T06:30:14.401364Z" } }, "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 = \"Aniridia\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Aniridia/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Aniridia/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Aniridia/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Aniridia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f4e48063", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "36dae91b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:30:14.403194Z", "iopub.status.busy": "2025-03-25T06:30:14.403049Z", "iopub.status.idle": "2025-03-25T06:30:14.632475Z", "shell.execute_reply": "2025-03-25T06:30:14.631989Z" } }, "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", "Potential Aniridia-related directories found: ['TCGA_Ocular_melanomas_(UVM)']\n", "Selected directory: TCGA_Ocular_melanomas_(UVM)\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', 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'clinical_M', 'clinical_N', 'clinical_T', 'clinical_stage', 'cytogenetic_abnormality', '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', 'extranocular_nodule_size', 'extrascleral_extension', 'extravascular_matrix_patterns', 'eye_color', 'form_completion_date', 'gender', 'gene_expression_profile', 'height', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_pathologic_diagnosis_method', 'initial_weight', 'is_ffpe', 'lost_follow_up', 'metastatic_site', 'mitotic_count', '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', 'other_metastatic_site', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_death_reason', 'patient_id', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'radiation_therapy', 'sample_type', 'sample_type_id', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_basal_diameter', 'tumor_basal_diameter_mx', 'tumor_infiltrating_lymphocytes', 'tumor_infiltrating_macrophages', 'tumor_morphology_percentage', 'tumor_shape_pathologic_clinical', 'tumor_thickness', 'tumor_thickness_measurement', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_UVM_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_UVM_gistic2thd', '_GENOMIC_ID_TCGA_UVM_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_UVM_miRNA_HiSeq', '_GENOMIC_ID_TCGA_UVM_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_UVM_exp_HiSeqV2', '_GENOMIC_ID_TCGA_UVM_gistic2', '_GENOMIC_ID_TCGA_UVM_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_UVM_mutation_bcm_gene', '_GENOMIC_ID_TCGA_UVM_hMethyl450', '_GENOMIC_ID_TCGA_UVM_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_UVM_mutation_broad_gene', '_GENOMIC_ID_TCGA_UVM_RPPA', '_GENOMIC_ID_TCGA_UVM_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_UVM_mutation_curated_broad_gene', '_GENOMIC_ID_TCGA_UVM_PDMRNAseq', '_GENOMIC_ID_data/public/TCGA/UVM/miRNA_HiSeq_gene']\n" ] } ], "source": [ "import os\n", "\n", "# Step 1: Look for directories related to Aniridia (a congenital eye disorder)\n", "tcga_subdirs = os.listdir(tcga_root_dir)\n", "print(f\"Available TCGA subdirectories: {tcga_subdirs}\")\n", "\n", "# Check if any directories contain relevant terms to Aniridia (eye-related)\n", "aniridia_related_terms = [\"eye\", \"ocular\", \"iris\", \"aniridia\", \"ophthalmologic\", \"uveal\"]\n", "potential_dirs = []\n", "\n", "for directory in tcga_subdirs:\n", " if any(term.lower() in directory.lower() for term in aniridia_related_terms):\n", " potential_dirs.append(directory)\n", "\n", "print(f\"Potential {trait}-related directories found: {potential_dirs}\")\n", "\n", "if potential_dirs:\n", " # Select the most specific match - TCGA_Ocular_melanomas_(UVM) is related to eye disorders\n", " target_dir = potential_dirs[0]\n", " target_path = os.path.join(tcga_root_dir, target_dir)\n", " \n", " print(f\"Selected directory: {target_dir}\")\n", " \n", " # Get the clinical and genetic data file paths\n", " clinical_path, genetic_path = tcga_get_relevant_filepaths(target_path)\n", " \n", " # Load the datasets\n", " clinical_df = pd.read_csv(clinical_path, sep='\\t', index_col=0)\n", " genetic_df = pd.read_csv(genetic_path, sep='\\t', index_col=0)\n", " \n", " # Print column names of clinical data\n", " print(\"\\nClinical data columns:\")\n", " print(clinical_df.columns.tolist())\n", " \n", " # Check if we have both gene data and potential trait data\n", " has_gene_data = not genetic_df.empty\n", " has_potential_trait_data = not clinical_df.empty\n", " \n", " # Record our initial assessment\n", " validate_and_save_cohort_info(\n", " is_final=False, \n", " cohort=\"TCGA\", \n", " info_path=json_path, \n", " is_gene_available=has_gene_data, \n", " is_trait_available=has_potential_trait_data\n", " )\n", "else:\n", " print(f\"No TCGA subdirectory contains terms directly related to {trait}.\")\n", " print(\"TCGA is primarily a cancer genomics database and may not have specific data for this condition.\")\n", " \n", " # Marking the trait as unavailable in the cohort_info.json\n", " validate_and_save_cohort_info(\n", " is_final=False, \n", " cohort=\"TCGA\", \n", " info_path=json_path, \n", " is_gene_available=False, \n", " is_trait_available=False\n", " )\n", " \n", " print(f\"Task completed: {trait} data not available in TCGA dataset.\")\n" ] }, { "cell_type": "markdown", "id": "2cc8e942", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "ffabd4fe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:30:14.633931Z", "iopub.status.busy": "2025-03-25T06:30:14.633808Z", "iopub.status.idle": "2025-03-25T06:30:14.640696Z", "shell.execute_reply": "2025-03-25T06:30:14.640393Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [47, 56, 54, 51, 76], 'days_to_birth': [-17514, -20539, -19894, -18948, -28025]}\n", "Gender columns preview:\n", "{'gender': ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'MALE']}\n" ] } ], "source": [ "# Identify candidate columns for age and gender\n", "candidate_age_cols = [\"age_at_initial_pathologic_diagnosis\", \"days_to_birth\"]\n", "candidate_gender_cols = [\"gender\"]\n", "\n", "# Let's access the clinical data\n", "cohort_dir = os.path.join(tcga_root_dir, \"TCGA_Ocular_melanomas_(UVM)\")\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n", "clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n", "\n", "# Extract and preview the candidate columns for age\n", "age_preview = {}\n", "if candidate_age_cols:\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", "# Extract and preview the candidate columns for gender\n", "gender_preview = {}\n", "if candidate_gender_cols:\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(\"Gender columns preview:\")\n", " print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "c5f3d764", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "7b194034", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:30:14.641916Z", "iopub.status.busy": "2025-03-25T06:30:14.641805Z", "iopub.status.idle": "2025-03-25T06:30:14.644455Z", "shell.execute_reply": "2025-03-25T06:30:14.644156Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected age values preview: [47, 56, 54, 51, 76]\n", "Selected gender column: gender\n", "Selected gender values preview: ['FEMALE', 'MALE', 'MALE', 'FEMALE', 'MALE']\n" ] } ], "source": [ "# Analyze the candidate columns for age and gender information\n", "\n", "# For age, we have two options: 'age_at_initial_pathologic_diagnosis' and 'days_to_birth'\n", "# 'age_at_initial_pathologic_diagnosis' has direct age values (in years)\n", "# 'days_to_birth' has negative values representing days before birth (need conversion)\n", "# Let's choose 'age_at_initial_pathologic_diagnosis' as it's more straightforward\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# For gender, we only have one candidate column: 'gender'\n", "# The values look appropriate ('MALE', 'FEMALE')\n", "gender_col = 'gender'\n", "\n", "# Print the selected columns with their preview values from the previous step output\n", "print(f\"Selected age column: {age_col}\")\n", "print(f\"Selected age values preview: {[47, 56, 54, 51, 76]}\")\n", "print(f\"Selected gender column: {gender_col}\")\n", "print(f\"Selected gender values preview: {['FEMALE', 'MALE', 'MALE', 'FEMALE', 'MALE']}\")\n" ] }, { "cell_type": "markdown", "id": "3a82004a", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "b3664395", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:30:14.645688Z", "iopub.status.busy": "2025-03-25T06:30:14.645582Z", "iopub.status.idle": "2025-03-25T06:30:22.232100Z", "shell.execute_reply": "2025-03-25T06:30:22.231705Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data saved to ../../output/preprocess/Aniridia/clinical_data/TCGA.csv\n", "Clinical data shape: (80, 3)\n", " Aniridia Age Gender\n", "sampleID \n", "TCGA-RZ-AB0B-01 1 47 0\n", "TCGA-V3-A9ZX-01 1 56 1\n", "TCGA-V3-A9ZY-01 1 54 1\n", "TCGA-V4-A9E5-01 1 51 0\n", "TCGA-V4-A9E7-01 1 76 1\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Aniridia/gene_data/TCGA.csv\n", "Normalized gene data shape: (19848, 80)\n", "Linked data shape: (80, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values - linked data shape: (80, 19851)\n", "Quartiles for 'Aniridia':\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 'Aniridia' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 51.0\n", " 50% (Median): 61.5\n", " 75%: 74.25\n", "Min: 22\n", "Max: 86\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 35 occurrences. This represents 43.75% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "After removing biased features - linked data shape: (80, 19851)\n", "Linked data not saved due to quality concerns\n" ] } ], "source": [ "# Step 1: Extract and standardize the clinical features\n", "# Get file paths using the selected ocular melanoma dataset from Step 1\n", "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Ocular_melanomas_(UVM)')\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Load data\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", "# Create standardized clinical features dataframe with trait, age, and gender\n", "# Using tumor/normal classification as the proxy for Aniridia-related trait\n", "clinical_features = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=trait, # Using predefined trait variable\n", " age_col=age_col, \n", " gender_col=gender_col\n", ")\n", "\n", "# Save clinical data\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", "print(clinical_features.head())\n", "\n", "# Step 2: Normalize gene symbols in gene expression data\n", "# Transpose the genetic data to have genes as rows\n", "genetic_data = genetic_df.copy()\n", "\n", "# Normalize gene symbols using the NCBI Gene database synonyms\n", "normalized_gene_data = normalize_gene_symbols_in_index(genetic_data)\n", "\n", "# Save normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "\n", "# Step 3: Link clinical and genetic data\n", "# Transpose genetic data to get samples as rows, genes as columns\n", "genetic_data_transposed = normalized_gene_data.T\n", "\n", "# Ensure clinical and genetic data have the same samples (index values)\n", "common_samples = clinical_features.index.intersection(genetic_data_transposed.index)\n", "clinical_subset = clinical_features.loc[common_samples]\n", "genetic_subset = genetic_data_transposed.loc[common_samples]\n", "\n", "# Combine clinical and genetic data\n", "linked_data = pd.concat([clinical_subset, genetic_subset], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# Step 4: Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait_col=trait)\n", "print(f\"After handling missing values - linked data shape: {linked_data.shape}\")\n", "\n", "# Step 5: Determine biased features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait)\n", "print(f\"After removing biased features - linked data shape: {linked_data.shape}\")\n", "\n", "# Step 6: Validate data quality and save cohort info\n", "# First check if we have both gene and trait data\n", "is_gene_available = linked_data.shape[1] > 3 # More than just trait, Age, Gender\n", "is_trait_available = trait in linked_data.columns\n", "\n", "# Take notes of special findings\n", "notes = f\"TCGA Ocular Melanomas dataset processed. Used tumor/normal classification as a proxy for {trait} analysis.\"\n", "\n", "# Validate the data quality\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,\n", " note=notes\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(\"Linked data not saved due to quality concerns\")" ] } ], "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 }