{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "1dca11f7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:04:29.582660Z", "iopub.status.busy": "2025-03-25T08:04:29.582431Z", "iopub.status.idle": "2025-03-25T08:04:29.748151Z", "shell.execute_reply": "2025-03-25T08:04:29.747708Z" } }, "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 = \"Endometriosis\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Endometriosis/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Endometriosis/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Endometriosis/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Endometriosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "1892d1ef", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "225962e1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:04:29.749575Z", "iopub.status.busy": "2025-03-25T08:04:29.749437Z", "iopub.status.idle": "2025-03-25T08:04:30.260587Z", "shell.execute_reply": "2025-03-25T08:04:30.260117Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found potential match: TCGA_Uterine_Carcinosarcoma_(UCS)\n", "Found potential match: TCGA_Endometrioid_Cancer_(UCEC)\n", "Selected as best match: TCGA_Endometrioid_Cancer_(UCEC)\n", "Selected directory: TCGA_Endometrioid_Cancer_(UCEC)\n", "Clinical file: TCGA.UCEC.sampleMap_UCEC_clinicalMatrix\n", "Genetic file: TCGA.UCEC.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['CDE_ID_3226963', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_DNAMethyl_UCEC', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_UCEC', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_surgery_locoregional_procedure', 'additional_treatment_completion_success_outcome', 'age_at_initial_pathologic_diagnosis', 'aln_pos_ihc', 'aln_pos_light_micro', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'birth_control_pill_history_usage_category', 'clinical_stage', 'colorectal_cancer', 'days_to_additional_surgery_metastatic_procedure', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_last_known_alive', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'diabetes', 'disease_code', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_of_neoadjuvant_treatment', 'horm_ther', 'hypertension', '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', 'menopause_status', 'neoplasm_histologic_grade', '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', 'pct_tumor_invasion', 'peritoneal_wash', 'person_neoplasm_cancer_status', 'pln_pos_ihc', 'pln_pos_light_micro', 'postoperative_rx_tx', 'pregnancies', 'primary_therapy_outcome_success', 'prior_tamoxifen_administered_usage_category', 'project_code', 'radiation_therapy', 'recurrence_second_surgery_neoplasm_surgical_procedure_name', 'recurrence_second_surgery_neoplasm_surgical_procedure_name_other', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'surgical_approach', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_aor_lnp', 'total_aor_lnr', 'total_pelv_lnp', 'total_pelv_lnr', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_UCEC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_data/public/TCGA/UCEC/miRNA_GA_gene', '_GENOMIC_ID_TCGA_UCEC_PDMRNAseq', '_GENOMIC_ID_TCGA_UCEC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_UCEC_RPPA_RBN', '_GENOMIC_ID_TCGA_UCEC_RPPA', '_GENOMIC_ID_TCGA_UCEC_PDMarrayCNV', '_GENOMIC_ID_TCGA_UCEC_miRNA_GA', '_GENOMIC_ID_TCGA_UCEC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_UCEC_mutation_broad_gene', '_GENOMIC_ID_TCGA_UCEC_mutation_wustl_gene', '_GENOMIC_ID_TCGA_UCEC_mutation', '_GENOMIC_ID_TCGA_UCEC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_UCEC_PDMarray', '_GENOMIC_ID_TCGA_UCEC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_UCEC_exp_GAV2', '_GENOMIC_ID_TCGA_UCEC_gistic2thd', '_GENOMIC_ID_TCGA_UCEC_G4502A_07_3', '_GENOMIC_ID_TCGA_UCEC_gistic2', '_GENOMIC_ID_data/public/TCGA/UCEC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_UCEC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_UCEC_hMethyl450', '_GENOMIC_ID_TCGA_UCEC_hMethyl27', '_GENOMIC_ID_TCGA_UCEC_exp_GAV2_exon']\n", "\n", "Clinical data shape: (596, 123)\n", "Genetic data shape: (20530, 201)\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# 1. Find the most relevant directory for Endometriosis\n", "subdirectories = os.listdir(tcga_root_dir)\n", "target_trait = trait.lower().replace(\"_\", \" \") # Convert to lowercase for case-insensitive matching\n", "\n", "# Search for related terms to Endometriosis\n", "related_terms = [\"endometrio\", \"uterine\", \"uterus\", \"endometrial\", \"ucec\"]\n", "matched_dir = None\n", "\n", "for subdir in subdirectories:\n", " subdir_lower = subdir.lower()\n", " # Check if any related term is in the directory name\n", " if any(term in subdir_lower for term in related_terms):\n", " matched_dir = subdir\n", " print(f\"Found potential match: {subdir}\")\n", " # If exact match found, select it\n", " if \"endometrio\" in subdir_lower:\n", " print(f\"Selected as best match: {subdir}\")\n", " matched_dir = subdir\n", " break\n", "\n", "# If we found a potential match, use it\n", "if matched_dir:\n", " print(f\"Selected directory: {matched_dir}\")\n", " \n", " # 2. Get the clinical and genetic data file paths\n", " cohort_dir = os.path.join(tcga_root_dir, matched_dir)\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 matched_dir:\n", " print(\"Skipping this trait as no suitable data was found.\")\n" ] }, { "cell_type": "markdown", "id": "0b61508d", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "624fcb20", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:04:30.262014Z", "iopub.status.busy": "2025-03-25T08:04:30.261883Z", "iopub.status.idle": "2025-03-25T08:04:30.273928Z", "shell.execute_reply": "2025-03-25T08:04:30.273539Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [59.0, 54.0, 69.0, 51.0, 67.0], 'days_to_birth': [nan, -19818.0, -25518.0, -18785.0, -24477.0]}\n", "Gender columns preview:\n", "{'gender': ['FEMALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']}\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", "# Load the clinical data file to access these columns\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, \"TCGA_Endometrioid_Cancer_(UCEC)\"))\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Extract and preview age columns\n", "if candidate_age_cols:\n", " age_preview_dict = {}\n", " for col in candidate_age_cols:\n", " if col in clinical_df.columns:\n", " age_preview_dict[col] = clinical_df[col].head(5).tolist()\n", " print(\"Age columns preview:\")\n", " print(age_preview_dict)\n", "\n", "# Extract and preview gender columns\n", "if candidate_gender_cols:\n", " gender_preview_dict = {}\n", " for col in candidate_gender_cols:\n", " if col in clinical_df.columns:\n", " gender_preview_dict[col] = clinical_df[col].head(5).tolist()\n", " print(\"Gender columns preview:\")\n", " print(gender_preview_dict)\n" ] }, { "cell_type": "markdown", "id": "9a2e5232", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "b5b4f86f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:04:30.275159Z", "iopub.status.busy": "2025-03-25T08:04:30.275044Z", "iopub.status.idle": "2025-03-25T08:04:30.277669Z", "shell.execute_reply": "2025-03-25T08:04:30.277286Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Chosen age column: age_at_initial_pathologic_diagnosis\n", "First 5 values from age column: [59.0, 54.0, 69.0, 51.0, 67.0]\n", "Chosen gender column: gender\n", "First 5 values from gender column: ['FEMALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']\n" ] } ], "source": [ "# Examine the age columns\n", "# 'age_at_initial_pathologic_diagnosis' has numeric values and appears to be the most direct\n", "# 'days_to_birth' has some missing values (nan) and would need conversion (negative values)\n", "\n", "# Examine the gender column\n", "# There is only one gender column 'gender' with values like 'FEMALE'\n", "\n", "# Select appropriate columns\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "gender_col = 'gender'\n", "\n", "# Print information about chosen columns\n", "print(f\"Chosen age column: {age_col}\")\n", "print(f\"First 5 values from age column: [59.0, 54.0, 69.0, 51.0, 67.0]\")\n", "\n", "print(f\"Chosen gender column: {gender_col}\")\n", "print(f\"First 5 values from gender column: ['FEMALE', 'FEMALE', 'FEMALE', 'FEMALE', 'FEMALE']\")\n" ] }, { "cell_type": "markdown", "id": "10b6f95e", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "a727f0b5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:04:30.278866Z", "iopub.status.busy": "2025-03-25T08:04:30.278759Z", "iopub.status.idle": "2025-03-25T08:04:51.898026Z", "shell.execute_reply": "2025-03-25T08:04:51.897617Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Endometriosis/gene_data/TCGA.csv\n", "Gene expression data shape after normalization: (19848, 201)\n", "Clinical data saved to ../../output/preprocess/Endometriosis/clinical_data/TCGA.csv\n", "Clinical data shape: (596, 3)\n", "Number of samples in clinical data: 596\n", "Number of samples in genetic data: 201\n", "Number of common samples: 201\n", "Linked data shape: (201, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (201, 19851)\n", "For the feature 'Endometriosis', the least common label is '0' with 24 occurrences. This represents 11.94% of the dataset.\n", "The distribution of the feature 'Endometriosis' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 58.0\n", " 50% (Median): 65.24598930481284\n", " 75%: 72.0\n", "Min: 33.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 201 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Endometriosis/TCGA.csv\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 }