{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "66bde4d7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:00:06.558111Z", "iopub.status.busy": "2025-03-25T04:00:06.557991Z", "iopub.status.idle": "2025-03-25T04:00:06.739441Z", "shell.execute_reply": "2025-03-25T04:00:06.739096Z" } }, "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 = \"Sjögrens_Syndrome\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Sjögrens_Syndrome/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Sjögrens_Syndrome/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Sjögrens_Syndrome/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Sjögrens_Syndrome/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "4c5a0368", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "4faf34b3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:00:06.741177Z", "iopub.status.busy": "2025-03-25T04:00:06.740789Z", "iopub.status.idle": "2025-03-25T04:00:08.248547Z", "shell.execute_reply": "2025-03-25T04:00:08.248195Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found matching directories: ['TCGA_Head_and_Neck_Cancer_(HNSC)']\n", "Selected directory: TCGA_Head_and_Neck_Cancer_(HNSC)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Clinical data columns:\n", "['_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_HNSC', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_HNSC', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_surgery_locoregional_procedure', 'additional_surgery_metastatic_procedure', 'age_at_initial_pathologic_diagnosis', 'alcohol_history_documented', 'amount_of_alcohol_consumption_per_day', 'anatomic_neoplasm_subdivision', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'clinical_M', 'clinical_N', 'clinical_T', 'clinical_stage', 'days_to_additional_surgery_locoregional_procedure', 'days_to_additional_surgery_metastatic_procedure', 'days_to_birth', 'days_to_collection', 'days_to_completion_of_curative_tx', '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', 'disease_after_curative_tx', 'egfr_amplication_status', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'frequency_of_alcohol_consumption', 'gender', 'histological_type', 'history_of_neoadjuvant_treatment', 'hpv_status_by_ish_testing', 'hpv_status_by_p16_testing', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'laterality', 'longest_dimension', 'lost_follow_up', 'lymph_node_examined_count', 'lymphnode_dissection_method_right', 'lymphnode_neck_dissection', 'lymphovascular_invasion_present', 'margin_status', 'method_of_curative_tx', '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', 'number_of_lymphnodes_positive_by_he', 'number_of_lymphnodes_positive_by_ihc', 'number_pack_years_smoked', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_death_reason', 'patient_id', 'perineural_invasion_present', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'presence_of_pathological_nodal_extracapsular_spread', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'progression_determined_by', 'radiation_therapy', 'sample_type', 'sample_type_id', 'shortest_dimension', 'smokeless_tobacco_use_age_at_quit', 'smokeless_tobacco_use_age_at_start', 'smokeless_tobacco_use_at_diag', 'smokeless_tobacco_use_per_day', 'smokeless_tobacco_use_regularly', 'stopped_smoking_year', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tobacco_smoking_history', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', 'year_of_tobacco_smoking_onset', '_GENOMIC_ID_TCGA_HNSC_mutation_curated_broad_gene', '_GENOMIC_ID_data/public/TCGA/HNSC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_HNSC_miRNA_GA', '_GENOMIC_ID_TCGA_HNSC_RPPA_RBN', '_GENOMIC_ID_TCGA_HNSC_mutation', '_GENOMIC_ID_TCGA_HNSC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_HNSC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_HNSC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_HNSC_mutation_bcgsc_gene', '_GENOMIC_ID_data/public/TCGA/HNSC/miRNA_GA_gene', '_GENOMIC_ID_TCGA_HNSC_hMethyl450', '_GENOMIC_ID_TCGA_HNSC_RPPA', '_GENOMIC_ID_TCGA_HNSC_gistic2', '_GENOMIC_ID_TCGA_HNSC_PDMRNAseq', '_GENOMIC_ID_TCGA_HNSC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_HNSC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_HNSC_mutation_broad_gene', '_GENOMIC_ID_TCGA_HNSC_gistic2thd', '_GENOMIC_ID_TCGA_HNSC_exp_HiSeqV2']\n" ] } ], "source": [ "# Step 1: Search for directories related to Sjögren's Syndrome\n", "import os\n", "\n", "# List all directories in TCGA root directory\n", "tcga_dirs = os.listdir(tcga_root_dir)\n", "\n", "# Look for directories related to Sjögren's Syndrome\n", "# Sjögren's might be associated with salivary gland issues or autoimmune responses affecting head and neck\n", "matching_dirs = [dir_name for dir_name in tcga_dirs \n", " if any(term in dir_name.lower() for term in \n", " [\"sjogren\", \"sjögren\", \"salivary\", \"autoimmune\", \"head_and_neck\"])]\n", "\n", "if not matching_dirs:\n", " print(f\"No matching directory found for trait: {trait}\")\n", " # Check if there are any potential related conditions we should explore\n", " related_conditions = [dir_name for dir_name in tcga_dirs if \"head_and_neck\" in dir_name.lower()]\n", " if related_conditions:\n", " print(f\"Potentially related conditions: {related_conditions}\")\n", " \n", " # Record that this trait is not available and exit\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", " print(\"Task marked as completed. Sjögren's Syndrome is not directly represented in the TCGA dataset.\")\n", "else:\n", " # If we found a matching directory\n", " print(f\"Found matching directories: {matching_dirs}\")\n", " \n", " # Select the most relevant directory\n", " selected_dir = matching_dirs[0]\n", " print(f\"Selected directory: {selected_dir}\")\n", " cohort_dir = os.path.join(tcga_root_dir, selected_dir)\n", " \n", " # Step 2: Get file paths for clinical and genetic data\n", " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", " \n", " # Step 3: Load the 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", " # Step 4: Print column names of clinical data\n", " print(\"Clinical data columns:\")\n", " print(clinical_df.columns.tolist())\n" ] }, { "cell_type": "markdown", "id": "d48ca82b", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "a23a260c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:00:08.249974Z", "iopub.status.busy": "2025-03-25T04:00:08.249678Z", "iopub.status.idle": "2025-03-25T04:00:08.262350Z", "shell.execute_reply": "2025-03-25T04:00:08.262017Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age column previews:\n", "{'age_at_initial_pathologic_diagnosis': [66.0, 69.0, 49.0, 39.0, 45.0], 'days_to_birth': [-24222.0, -25282.0, -17951.0, -14405.0, -16536.0]}\n", "Gender column previews:\n", "{'gender': ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']}\n" ] } ], "source": [ "# Finding candidate demographic features\n", "candidate_age_cols = [\"age_at_initial_pathologic_diagnosis\", \"days_to_birth\"]\n", "candidate_gender_cols = [\"gender\"]\n", "\n", "# Extract and preview candidate columns\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, \"TCGA_Head_and_Neck_Cancer_(HNSC)\"))\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Extract 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", "print(\"Age column previews:\")\n", "print(age_preview)\n", "\n", "# Extract 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(\"Gender column previews:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "3a47c3dd", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "b3cc6ad4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:00:08.263592Z", "iopub.status.busy": "2025-03-25T04:00:08.263400Z", "iopub.status.idle": "2025-03-25T04:00:08.265842Z", "shell.execute_reply": "2025-03-25T04:00:08.265539Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Chosen age column: age_at_initial_pathologic_diagnosis\n", "Chosen gender column: gender\n" ] } ], "source": [ "# Analyzing candidate columns for demographic information\n", "\n", "# For age information, we have two candidates:\n", "# 1. 'age_at_initial_pathologic_diagnosis' - contains actual age values in years\n", "# 2. 'days_to_birth' - contains negative values representing days from birth to diagnosis\n", "\n", "# The 'age_at_initial_pathologic_diagnosis' provides age directly in years, which is more \n", "# intuitive and easier to work with than 'days_to_birth'\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# For gender information, we only have one candidate:\n", "# 'gender' - contains values like 'MALE' and 'FEMALE'\n", "gender_col = 'gender'\n", "\n", "# Print information about the chosen columns\n", "print(f\"Chosen age column: {age_col}\")\n", "print(f\"Chosen gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "19d146cf", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "4c51b50f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:00:08.266986Z", "iopub.status.busy": "2025-03-25T04:00:08.266851Z", "iopub.status.idle": "2025-03-25T04:01:03.132694Z", "shell.execute_reply": "2025-03-25T04:01:03.132223Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Saved clinical data with 604 samples\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 19848 genes remaining\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene expression data\n", "Linked data shape: (566, 19851) (samples x features)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (566, 19851)\n", "For the feature 'Sjögrens_Syndrome', the least common label is '0' with 44 occurrences. This represents 7.77% of the dataset.\n", "The distribution of the feature 'Sjögrens_Syndrome' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 53.0\n", " 50% (Median): 61.0\n", " 75%: 68.0\n", "Min: 19.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' with 151 occurrences. This represents 26.68% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved usable linked data to ../../output/preprocess/Sjögrens_Syndrome/TCGA.csv\n" ] } ], "source": [ "# Step 1: Extract and standardize clinical features\n", "# Use the Head and Neck Cancer directory identified in Step 1\n", "selected_dir = 'TCGA_Head_and_Neck_Cancer_(HNSC)'\n", "cohort_dir = os.path.join(tcga_root_dir, selected_dir)\n", "\n", "# Get the file paths for clinical and genetic data\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Load the 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", "# Extract standardized clinical features using the provided trait variable\n", "clinical_features = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=trait, # Using the provided trait variable\n", " age_col=age_col, \n", " gender_col=gender_col\n", ")\n", "\n", "# Save the clinical data to out_clinical_data_file\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\"Saved clinical data with {len(clinical_features)} samples\")\n", "\n", "# Step 2: Normalize gene symbols in gene expression data\n", "# Transpose to get genes as rows\n", "gene_df = genetic_df\n", "\n", "# Normalize gene symbols using NCBI Gene database synonyms\n", "normalized_gene_df = normalize_gene_symbols_in_index(gene_df)\n", "print(f\"After normalization: {len(normalized_gene_df)} genes remaining\")\n", "\n", "# Save the normalized gene expression 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\"Saved normalized gene expression data\")\n", "\n", "# Step 3: Link clinical and genetic data\n", "# Merge clinical features with genetic expression data\n", "linked_data = clinical_features.join(normalized_gene_df.T, how='inner')\n", "print(f\"Linked data shape: {linked_data.shape} (samples x features)\")\n", "\n", "# Step 4: Handle missing values\n", "cleaned_data = handle_missing_values(linked_data, trait_col=trait)\n", "print(f\"After handling missing values, data shape: {cleaned_data.shape}\")\n", "\n", "# Step 5: Determine if trait or demographics are severely biased\n", "trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait=trait)\n", "\n", "# Step 6: Validate data quality and save cohort information\n", "note = \"The dataset contains gene expression data along with clinical information for head and neck cancer patients, which is relevant for studying Sjögren's Syndrome as it often affects salivary glands in the head and neck region.\"\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=cleaned_data,\n", " note=note\n", ")\n", "\n", "# Step 7: Save the linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Saved usable linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset was determined to be unusable and was 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 }