{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ea4e4b5e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:44:24.643857Z", "iopub.status.busy": "2025-03-25T03:44:24.643618Z", "iopub.status.idle": "2025-03-25T03:44:24.813079Z", "shell.execute_reply": "2025-03-25T03:44:24.812738Z" } }, "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 = \"Psoriasis\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Psoriasis/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Psoriasis/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Psoriasis/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Psoriasis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "7da519b5", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "23eb0dfc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:44:24.814516Z", "iopub.status.busy": "2025-03-25T03:44:24.814375Z", "iopub.status.idle": "2025-03-25T03:44:25.945837Z", "shell.execute_reply": "2025-03-25T03:44:25.945470Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Looking for a relevant directory for Psoriasis among 38 TCGA directories\n", "Selected TCGA_Melanoma_(SKCM) as the most relevant directory for Psoriasis\n", "Clinical data file: TCGA.SKCM.sampleMap_SKCM_clinicalMatrix\n", "Genetic data file: TCGA.SKCM.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Clinical data shape: (481, 93)\n", "Genetic data shape: (20530, 474)\n", "\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', '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" ] } ], "source": [ "import os\n", "import pandas as pd\n", "\n", "# Step 1: Review TCGA subdirectories to find the most relevant one for Psoriasis\n", "available_dirs = os.listdir(tcga_root_dir)\n", "print(f\"Looking for a relevant directory for {trait} among {len(available_dirs)} TCGA directories\")\n", "\n", "# Psoriasis is a skin condition. TCGA_Melanoma_(SKCM) is the closest match as it deals with skin cancer\n", "# While not the same disease, it's the closest skin-related dataset in TCGA\n", "relevant_dir = \"TCGA_Melanoma_(SKCM)\"\n", "\n", "# Check if our chosen directory exists\n", "if relevant_dir not in available_dirs:\n", " print(f\"No suitable directory found for {trait}. The closest candidate would be {relevant_dir}.\")\n", " # Record this information and exit\n", " validate_and_save_cohort_info(is_final=False, cohort=\"TCGA\", info_path=json_path, \n", " is_gene_available=False, is_trait_available=False)\n", " exit()\n", "else:\n", " print(f\"Selected {relevant_dir} as the most relevant directory for {trait}\")\n", " \n", " # Step 2: Identify paths to clinical and genetic data files\n", " cohort_dir = os.path.join(tcga_root_dir, relevant_dir)\n", " clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", " \n", " print(f\"Clinical data file: {os.path.basename(clinical_file_path)}\")\n", " print(f\"Genetic data file: {os.path.basename(genetic_file_path)}\")\n", " \n", " # Step 3: Load the clinical and genetic data files\n", " try:\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", " print(f\"Clinical data shape: {clinical_df.shape}\")\n", " print(f\"Genetic data shape: {genetic_df.shape}\")\n", " \n", " # Step 4: Print the column names of the clinical data\n", " print(\"\\nClinical data columns:\")\n", " print(clinical_df.columns.tolist())\n", " \n", " # Check if both datasets have data\n", " is_gene_available = genetic_df.shape[0] > 0 and genetic_df.shape[1] > 0\n", " is_trait_available = clinical_df.shape[0] > 0 and clinical_df.shape[1] > 0\n", " \n", " # Record initial validation\n", " validate_and_save_cohort_info(is_final=False, cohort=\"TCGA\", info_path=json_path, \n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n", " \n", " except Exception as e:\n", " print(f\"Error loading data: {e}\")\n", " validate_and_save_cohort_info(is_final=False, cohort=\"TCGA\", info_path=json_path, \n", " is_gene_available=False, is_trait_available=False)\n" ] }, { "cell_type": "markdown", "id": "61f40c3f", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "c133dc38", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:44:25.947053Z", "iopub.status.busy": "2025-03-25T03:44:25.946942Z", "iopub.status.idle": "2025-03-25T03:44:25.956011Z", "shell.execute_reply": "2025-03-25T03:44:25.955719Z" } }, "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", "Gender columns preview:\n", "{'gender': ['MALE', 'MALE', 'MALE', '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", "# Get clinical data file path\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(f\"{tcga_root_dir}/TCGA_Melanoma_(SKCM)\")\n", "\n", "# Load clinical data\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Extract and preview candidate age columns\n", "if candidate_age_cols:\n", " age_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_age_cols}\n", " print(\"Age columns preview:\")\n", " print(age_preview)\n", "\n", "# Extract and preview candidate gender columns\n", "if candidate_gender_cols:\n", " gender_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_gender_cols}\n", " print(\"Gender columns preview:\")\n", " print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "332e1189", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "92a2ab8b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:44:25.957042Z", "iopub.status.busy": "2025-03-25T03:44:25.956922Z", "iopub.status.idle": "2025-03-25T03:44:25.959085Z", "shell.execute_reply": "2025-03-25T03:44:25.958806Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# 1. Select appropriate columns for age and gender\n", "\n", "# Age column selection\n", "# Both columns seem to contain valid age information\n", "# 'age_at_initial_pathologic_diagnosis' is more directly usable as it's already in years\n", "# 'days_to_birth' would need conversion (it's negative days from birth to diagnosis)\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# Gender column selection\n", "# The 'gender' column looks appropriate with valid values ('MALE', 'FEMALE')\n", "gender_col = 'gender'\n", "\n", "# 2. Print the chosen columns\n", "print(f\"Selected age column: {age_col}\")\n", "print(f\"Selected gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "78c3b4e5", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "b1e4b40b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:44:25.960017Z", "iopub.status.busy": "2025-03-25T03:44:25.959908Z", "iopub.status.idle": "2025-03-25T03:44:39.169541Z", "shell.execute_reply": "2025-03-25T03:44:39.168991Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Processed clinical data (shape: (481, 3)) saved to ../../output/preprocess/Psoriasis/clinical_data/TCGA.csv\n", "Clinical data preview:\n", " Psoriasis Age Gender\n", "sampleID \n", "TCGA-3N-A9WB-06 1 71.0 1.0\n", "TCGA-3N-A9WC-06 1 82.0 1.0\n", "TCGA-3N-A9WD-06 1 82.0 1.0\n", "TCGA-BF-A1PU-01 1 46.0 0.0\n", "TCGA-BF-A1PV-01 1 74.0 0.0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original genetic data shape: (20530, 474)\n", "Normalized genetic data shape: (19848, 474)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Processed gene data saved to ../../output/preprocess/Psoriasis/gene_data/TCGA.csv\n", "Number of common samples between clinical and genetic data: 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 'Psoriasis', the least common label is '0' with 1 occurrences. This represents 0.21% of the dataset.\n", "The distribution of the feature 'Psoriasis' 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", "Is the trait distribution biased? True\n", "Data shape after removing biased features: (474, 19851)\n", "Data was deemed not usable for Psoriasis analysis - no final file saved.\n" ] } ], "source": [ "# 1. Extract and standardize clinical features\n", "# Use tcga_select_clinical_features to extract trait (Psoriasis) and demographic info\n", "# For TCGA datasets, we use sample ID patterns to determine the trait (tumor vs normal)\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(f\"{tcga_root_dir}/TCGA_Melanoma_(SKCM)\")\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "selected_clinical_df = tcga_select_clinical_features(clinical_df, trait, age_col, gender_col)\n", "\n", "# Save the processed clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Processed clinical data (shape: {selected_clinical_df.shape}) saved to {out_clinical_data_file}\")\n", "print(f\"Clinical data preview:\")\n", "print(selected_clinical_df.head())\n", "\n", "# 2. Normalize gene symbols in the genetic data\n", "genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n", "print(f\"Original genetic data shape: {genetic_df.shape}\")\n", "\n", "# Apply normalization using the NCBI Gene database\n", "normalized_genetic_df = normalize_gene_symbols_in_index(genetic_df)\n", "print(f\"Normalized genetic data shape: {normalized_genetic_df.shape}\")\n", "\n", "# Save the normalized gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_genetic_df.to_csv(out_gene_data_file)\n", "print(f\"Processed gene data saved to {out_gene_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "# In TCGA datasets, we need to ensure that indexes (sample IDs) match between datasets\n", "common_samples = set(selected_clinical_df.index).intersection(set(normalized_genetic_df.columns))\n", "print(f\"Number of common samples between clinical and genetic data: {len(common_samples)}\")\n", "\n", "# Filter both dataframes to include only common samples\n", "selected_clinical_df = selected_clinical_df.loc[selected_clinical_df.index.isin(common_samples)]\n", "normalized_genetic_df = normalized_genetic_df[list(common_samples)]\n", "\n", "# Combine clinical and genetic data\n", "linked_data = selected_clinical_df.join(normalized_genetic_df.T)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine if trait and demographic features are biased\n", "is_biased, cleaned_data = judge_and_remove_biased_features(linked_data, trait)\n", "print(f\"Is the trait distribution biased? {is_biased}\")\n", "print(f\"Data shape after removing biased features: {cleaned_data.shape}\")\n", "\n", "# 6. Validate the quality of the data and save metadata\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=is_biased,\n", " df=cleaned_data,\n", " note=f\"Data from TCGA Melanoma (SKCM) cohort was used as a proxy for {trait}.\"\n", ")\n", "\n", "# 7. Save the linked data if it's 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\"Final processed data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data was deemed not usable for {trait} analysis - no final file 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 }