{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "4856a60f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:40.426593Z", "iopub.status.busy": "2025-03-25T06:12:40.426417Z", "iopub.status.idle": "2025-03-25T06:12:40.591004Z", "shell.execute_reply": "2025-03-25T06:12:40.590666Z" } }, "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 = \"Pheochromocytoma_and_Paraganglioma\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Pheochromocytoma_and_Paraganglioma/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Pheochromocytoma_and_Paraganglioma/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Pheochromocytoma_and_Paraganglioma/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Pheochromocytoma_and_Paraganglioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "42569ebd", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "b28c1f77", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:40.592393Z", "iopub.status.busy": "2025-03-25T06:12:40.592253Z", "iopub.status.idle": "2025-03-25T06:12:41.063764Z", "shell.execute_reply": "2025-03-25T06:12:41.063438Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data columns:\n", "['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'ct_scan', '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', 'disease_detected_on_screening', 'eastern_cancer_oncology_group', 'form_completion_date', 'gender', 'histological_type', 'history_of_neoadjuvant_treatment', 'history_pheo_or_para_anatomic_site', 'history_pheo_or_para_include_benign', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'is_ffpe', 'karnofsky_performance_score', 'laterality', 'lost_follow_up', 'lymph_node_examined_count', 'new_neoplasm_confirmed_diagnosis_method_name', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_after_initial_treatment', 'number_of_lymphnodes_positive_by_he', 'oct_embedded', 'other_dx', 'outside_adrenal', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'radiation_therapy', 'sample_type', 'sample_type_id', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'tumor_tissue_site_other', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_PCPG_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_PCPG_mutation_bcm_gene', '_GENOMIC_ID_TCGA_PCPG_mutation_broad_gene', '_GENOMIC_ID_TCGA_PCPG_hMethyl450', '_GENOMIC_ID_TCGA_PCPG_gistic2thd', '_GENOMIC_ID_TCGA_PCPG_exp_HiSeqV2', '_GENOMIC_ID_TCGA_PCPG_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_PCPG_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_PCPG_miRNA_HiSeq', '_GENOMIC_ID_data/public/TCGA/PCPG/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_PCPG_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_PCPG_RPPA', '_GENOMIC_ID_TCGA_PCPG_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_PCPG_gistic2', '_GENOMIC_ID_TCGA_PCPG_PDMRNAseq', '_GENOMIC_ID_TCGA_PCPG_exp_HiSeqV2_percentile']\n" ] } ], "source": [ "# Step 1: Find the directory corresponding to Pheochromocytoma_and_Paraganglioma\n", "import os\n", "\n", "# List all directories in TCGA root directory\n", "tcga_dirs = os.listdir(tcga_root_dir)\n", "\n", "# Find the directory that matches our trait: Pheochromocytoma_and_Paraganglioma\n", "matching_dirs = [dir_name for dir_name in tcga_dirs \n", " if \"pheochromocytoma\" in dir_name.lower() or \"paraganglioma\" in dir_name.lower()]\n", "\n", "if not matching_dirs:\n", " print(f\"No matching directory found for trait: {trait}\")\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", "else:\n", " # Select the most relevant directory\n", " selected_dir = matching_dirs[0] # Should be 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)'\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": "5d8f7761", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "1480864e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:41.065181Z", "iopub.status.busy": "2025-03-25T06:12:41.064950Z", "iopub.status.idle": "2025-03-25T06:12:41.072680Z", "shell.execute_reply": "2025-03-25T06:12:41.072391Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found cohort directory: ../../input/TCGA/TCGA_Pheochromocytoma_Paraganglioma_(PCPG)\n", "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [78, 21, 21, 48, 48], 'days_to_birth': [-28497, -7834, -7834, -17790, -17790]}\n", "\n", "Gender columns preview:\n", "{'gender': ['FEMALE', 'FEMALE', 'FEMALE', 'MALE', '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", "# First, we need to find the correct directory for the trait\n", "# List all directories in the TCGA root dir to find the one for Pheochromocytoma and Paraganglioma\n", "tcga_dirs = os.listdir(tcga_root_dir)\n", "\n", "# Find directories that might correspond to Pheochromocytoma and Paraganglioma\n", "# Common abbreviation for this trait is PCPG\n", "cohort_dir = None\n", "for dir_name in tcga_dirs:\n", " if \"PCPG\" in dir_name or \"Pheochromocytoma\" in dir_name or \"Paraganglioma\" in dir_name:\n", " cohort_dir = os.path.join(tcga_root_dir, dir_name)\n", " break\n", "\n", "if cohort_dir is None:\n", " # If no matching directory is found, print available directories\n", " print(f\"Available directories in {tcga_root_dir}:\")\n", " print(tcga_dirs)\n", " raise FileNotFoundError(f\"Could not find directory for {trait} in {tcga_root_dir}\")\n", "else:\n", " print(f\"Found cohort directory: {cohort_dir}\")\n", "\n", "# Get the clinical file path\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Load the clinical data\n", "clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n", "\n", "# Preview 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 columns preview:\")\n", "print(age_preview)\n", "\n", "# Preview 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(\"\\nGender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "af933e38", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "2a926c8c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:41.073853Z", "iopub.status.busy": "2025-03-25T06:12:41.073748Z", "iopub.status.idle": "2025-03-25T06:12:41.076868Z", "shell.execute_reply": "2025-03-25T06:12:41.076591Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining age columns...\n", "age_at_initial_pathologic_diagnosis: [78, 21, 21, 48, 48]\n", " Missing values: 0\n", " Data type: \n", "days_to_birth: [-28497, -7834, -7834, -17790, -17790]\n", " Missing values: 0\n", " Data type: \n", "\n", "Examining gender columns...\n", "gender: ['FEMALE', 'FEMALE', 'FEMALE', 'MALE', 'MALE']\n", " Missing values: 0\n", " Unique values: {'FEMALE', 'MALE'}\n", "\n", "Chosen demographic columns:\n", " Age column: age_at_initial_pathologic_diagnosis\n", " Gender column: gender\n" ] } ], "source": [ "# Examine the age columns\n", "print(\"Examining age columns...\")\n", "for col_name, values in {'age_at_initial_pathologic_diagnosis': [78, 21, 21, 48, 48], \n", " 'days_to_birth': [-28497, -7834, -7834, -17790, -17790]}.items():\n", " print(f\"{col_name}: {values}\")\n", " print(f\" Missing values: {values.count(None) if None in values else 0}\")\n", " print(f\" Data type: {type(values[0])}\")\n", "\n", "# Examine the gender columns\n", "print(\"\\nExamining gender columns...\")\n", "for col_name, values in {'gender': ['FEMALE', 'FEMALE', 'FEMALE', 'MALE', 'MALE']}.items():\n", " print(f\"{col_name}: {values}\")\n", " print(f\" Missing values: {values.count(None) if None in values else 0}\")\n", " print(f\" Unique values: {set(values)}\")\n", "\n", "# Select appropriate columns\n", "age_col = 'age_at_initial_pathologic_diagnosis' # Direct age values in years\n", "gender_col = 'gender' # Clear gender labels\n", "\n", "print(\"\\nChosen demographic columns:\")\n", "print(f\" Age column: {age_col}\")\n", "print(f\" Gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "a01ce760", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "71d6181c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:41.077956Z", "iopub.status.busy": "2025-03-25T06:12:41.077857Z", "iopub.status.idle": "2025-03-25T06:12:49.704109Z", "shell.execute_reply": "2025-03-25T06:12:49.703766Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Saved clinical data with 187 samples\n", "After normalization: 19848 genes remaining\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene expression data\n", "Linked data shape: (187, 19851) (samples x features)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (187, 19851)\n", "For the feature 'Pheochromocytoma_and_Paraganglioma', the least common label is '0' with 3 occurrences. This represents 1.60% of the dataset.\n", "The distribution of the feature 'Pheochromocytoma_and_Paraganglioma' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 35.0\n", " 50% (Median): 46.0\n", " 75%: 57.5\n", "Min: 19\n", "Max: 83\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1' with 84 occurrences. This represents 44.92% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Dataset was determined to be unusable and was not saved.\n" ] } ], "source": [ "# Step 1: Extract and standardize clinical features\n", "# Find matching directory for Pheochromocytoma_and_Paraganglioma\n", "matching_dirs = [dir_name for dir_name in os.listdir(tcga_root_dir) \n", " if \"pheochromocytoma\" in dir_name.lower() or \"paraganglioma\" in dir_name.lower()]\n", "selected_dir = matching_dirs[0] # Should find 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)'\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 pheochromocytoma and paraganglioma patients.\"\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 }