{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "be46ca3c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:20:37.356533Z", "iopub.status.busy": "2025-03-25T06:20:37.356357Z", "iopub.status.idle": "2025-03-25T06:20:37.521450Z", "shell.execute_reply": "2025-03-25T06:20:37.521023Z" } }, "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 = \"Acute_Myeloid_Leukemia\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Acute_Myeloid_Leukemia/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Acute_Myeloid_Leukemia/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Acute_Myeloid_Leukemia/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Acute_Myeloid_Leukemia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "96c766f9", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "74c6204b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:20:37.522938Z", "iopub.status.busy": "2025-03-25T06:20:37.522798Z", "iopub.status.idle": "2025-03-25T06:20:37.963669Z", "shell.execute_reply": "2025-03-25T06:20:37.962939Z" } }, "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", "Selected directory: TCGA_Acute_Myeloid_Leukemia_(LAML)\n", "Clinical data file: ../../input/TCGA/TCGA_Acute_Myeloid_Leukemia_(LAML)/TCGA.LAML.sampleMap_LAML_clinicalMatrix\n", "Genetic data file: ../../input/TCGA/TCGA_Acute_Myeloid_Leukemia_(LAML)/TCGA.LAML.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['FISH_test_component', 'FISH_test_component_percentage_value', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_LAML', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_LAML', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'acute_myeloid_leukemia_calgb_cytogenetics_risk_category', 'age_at_initial_pathologic_diagnosis', 'atra_exposure', 'cumulative_agent_total_dose', 'cytogenetic_abnormality', 'cytogenetic_abnormality_other', 'cytogenetic_analysis_performed_ind', 'days_to_birth', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'disease_detection_molecular_analysis_method_type', 'fish_evaluation_performed_ind', 'fluorescence_in_situ_hybrid_cytogenetics_metaphase_ncls_rslt_cnt', 'fluorescence_in_situ_hybridization_abnormal_result_indicator', 'form_completion_date', 'gender', 'history_of_neoadjuvant_treatment', 'hydroxyurea_administration_prior_registration_clinicl_stdy_ndctr', 'hydroxyurea_agent_administered_day_count', 'immunophenotype_cytochemistry_testing_result', 'informed_consent_verified', 'is_ffpe', 'lab_procedure_abnormal_lymphocyte_result_percent_value', 'lab_procedure_blast_cell_outcome_percentage_value', 'lab_procedure_bone_marrow_band_cell_result_percent_value', 'lab_procedure_bone_marrow_basophil_result_percent_value', 'lab_procedure_bone_marrow_blast_cell_outcome_percent_value', 'lab_procedure_bone_marrow_cellularity_outcome_percent_value', 'lab_procedure_bone_marrow_lymphocyte_outcome_percent_value', 'lab_procedure_bone_marrow_metamyelocyte_result_value', 'lab_procedure_bone_marrow_myelocyte_result_percent_value', 'lab_procedure_bone_marrow_neutrophil_result_percent_value', 'lab_procedure_bone_marrow_prolymphocyte_result_percent_value', 'lab_procedure_bone_marrow_promonocyte_count_result_percent_value', 'lab_procedure_bone_marrow_promyelocyte_result_percent_value', 'lab_procedure_hematocrit_outcome_percent_value', 'lab_procedure_hemoglobin_result_specified_value', 'lab_procedure_leukocyte_result_unspecified_value', 'lab_procedure_monocyte_result_percent_value', 'lab_procedure_platelet_result_specified_value', 'leukemia_french_american_british_morphology_code', 'leukemia_specimen_cell_source_type', 'molecular_analysis_abnormal_result_indicator', 'molecular_analysis_abnormality_testing_result', 'molecular_analysis_performed_indicator', 'patient_id', 'person_history_nonmedical_leukemia_causing_agent_type', 'prior_dx', 'prior_hematologic_disorder_diagnosis_indicator', 'sample_type', 'sample_type_id', 'steroid_therapy_administered', 'tissue_source_site', 'total_dose_units', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_LAML_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LAML_hMethyl27', '_GENOMIC_ID_TCGA_LAML_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LAML_miRNA_GA', '_GENOMIC_ID_data/public/TCGA/LAML/miRNA_GA_gene', '_GENOMIC_ID_TCGA_LAML_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LAML_mutation_wustl_hiseq_gene', '_GENOMIC_ID_TCGA_LAML_exp_GA_exon', '_GENOMIC_ID_TCGA_LAML_gistic2', '_GENOMIC_ID_TCGA_LAML_exp_GA', '_GENOMIC_ID_TCGA_LAML_hMethyl450', '_GENOMIC_ID_TCGA_LAML_mutation', '_GENOMIC_ID_TCGA_LAML_PDMRNAseq', '_GENOMIC_ID_TCGA_LAML_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_LAML_gistic2thd', '_GENOMIC_ID_TCGA_LAML_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_LAML_mutation_wustl_gene']\n", "\n", "Clinical data shape: (200, 91)\n", "Genetic data shape: (20530, 173)\n" ] } ], "source": [ "import os\n", "\n", "# Step 1: Identify the most relevant directory for Acute Myeloid Leukemia\n", "tcga_subdirs = os.listdir(tcga_root_dir)\n", "print(f\"Available TCGA subdirectories: {tcga_subdirs}\")\n", "\n", "# Look for directories related to Acute Myeloid Leukemia\n", "target_dir = None\n", "for subdir in tcga_subdirs:\n", " if \"Leukemia\" in subdir and \"Acute\" in subdir and \"Myeloid\" in subdir:\n", " target_dir = subdir\n", " break\n", "\n", "if target_dir is None:\n", " print(f\"No suitable directory found for {trait}.\")\n", " # Mark the task as completed by creating a JSON record indicating data is not available\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() # Exit the program\n", "\n", "# Step 2: Get file paths for the selected directory\n", "cohort_dir = os.path.join(tcga_root_dir, target_dir)\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "print(f\"Selected directory: {target_dir}\")\n", "print(f\"Clinical data file: {clinical_file_path}\")\n", "print(f\"Genetic data file: {genetic_file_path}\")\n", "\n", "# Step 3: Load clinical and genetic data\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", "# Step 4: Print column names of clinical data\n", "print(\"\\nClinical data columns:\")\n", "print(clinical_df.columns.tolist())\n", "\n", "# Additional basic information\n", "print(f\"\\nClinical data shape: {clinical_df.shape}\")\n", "print(f\"Genetic data shape: {genetic_df.shape}\")\n" ] }, { "cell_type": "markdown", "id": "9a53de26", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "7881f14f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:20:37.965625Z", "iopub.status.busy": "2025-03-25T06:20:37.965466Z", "iopub.status.idle": "2025-03-25T06:20:37.974207Z", "shell.execute_reply": "2025-03-25T06:20:37.973664Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [50, 61, 30, 77, 46], 'days_to_birth': [-18385, -22584, -11203, -28124, -16892]}\n", "\n", "Gender columns preview:\n", "{'gender': ['MALE', 'FEMALE', 'MALE', 'MALE', 'MALE']}\n" ] } ], "source": [ "# 1. 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", "# 2. Extract and preview the candidate columns\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, 'TCGA_Acute_Myeloid_Leukemia_(LAML)'))\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "# Extract and 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", "print(\"Age columns preview:\")\n", "print(age_preview)\n", "\n", "# Extract and 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", "print(\"\\nGender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "9ef79128", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "651fd9e5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:20:37.975868Z", "iopub.status.busy": "2025-03-25T06:20:37.975760Z", "iopub.status.idle": "2025-03-25T06:20:37.978990Z", "shell.execute_reply": "2025-03-25T06:20:37.978482Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# Select age column - both columns seem to have data but age_at_initial_pathologic_diagnosis is more intuitive\n", "age_col = \"age_at_initial_pathologic_diagnosis\"\n", "\n", "# Select gender column - only one option available and it appears to have consistent data\n", "gender_col = \"gender\"\n", "\n", "# 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": "54884be7", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "7bd1d64c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:20:37.980613Z", "iopub.status.busy": "2025-03-25T06:20:37.980511Z", "iopub.status.idle": "2025-03-25T06:20:46.254993Z", "shell.execute_reply": "2025-03-25T06:20:46.254404Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data saved to ../../output/preprocess/Acute_Myeloid_Leukemia/clinical_data/TCGA.csv\n", "Clinical data shape: (200, 3)\n", " AML Age Gender\n", "sampleID \n", "TCGA-AB-2802-03 1 50 1\n", "TCGA-AB-2803-03 1 61 0\n", "TCGA-AB-2804-03 1 30 1\n", "TCGA-AB-2805-03 1 77 1\n", "TCGA-AB-2806-03 1 46 1\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Acute_Myeloid_Leukemia/gene_data/TCGA.csv\n", "Normalized gene data shape: (19848, 173)\n", "Linked data shape: (173, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values - linked data shape: (173, 19851)\n", "Quartiles for 'AML':\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 'AML' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 44.0\n", " 50% (Median): 58.0\n", " 75%: 67.0\n", "Min: 18\n", "Max: 88\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 80 occurrences. This represents 46.24% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "After removing biased features - linked data shape: (173, 19851)\n", "Linked data not saved due to quality concerns\n" ] } ], "source": [ "# Step 1: Extract and standardize the clinical features\n", "# Get file paths\n", "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Acute_Myeloid_Leukemia_(LAML)')\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", "clinical_features = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=\"AML\", # Using \"AML\" as the trait name\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=\"AML\")\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=\"AML\")\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 AML, Age, Gender\n", "is_trait_available = \"AML\" in linked_data.columns\n", "\n", "# Take notes of special findings\n", "notes = \"TCGA AML dataset successfully processed. Contains tumor samples (AML=1) and normal samples (AML=0).\"\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 }