{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6ed7380a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:03:25.360201Z", "iopub.status.busy": "2025-03-25T04:03:25.359776Z", "iopub.status.idle": "2025-03-25T04:03:25.530254Z", "shell.execute_reply": "2025-03-25T04:03:25.529905Z" } }, "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 = \"Stomach_Cancer\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Stomach_Cancer/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Stomach_Cancer/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Stomach_Cancer/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Stomach_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ed6696b2", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "206ccee9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:03:25.531674Z", "iopub.status.busy": "2025-03-25T04:03:25.531538Z", "iopub.status.idle": "2025-03-25T04:03:26.683786Z", "shell.execute_reply": "2025-03-25T04:03:26.683394Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found matching directories: ['TCGA_Stomach_Cancer_(STAD)']\n", "Selected directory: TCGA_Stomach_Cancer_(STAD)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Clinical data columns:\n", "['CDE_ID_3226963', '_INTEGRATION', '_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', 'anatomic_neoplasm_subdivision', 'antireflux_treatment', 'antireflux_treatment_type', 'barretts_esophagus', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'city_of_procurement', 'country_of_procurement', 'days_to_additional_surgery_locoregional_procedure', '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_new_tumor_event_after_initial_treatment', 'family_history_of_stomach_cancer', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'h_pylori_infection', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'longest_dimension', 'lost_follow_up', 'lymph_node_examined_count', 'neoplasm_histologic_grade', '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', 'number_of_relatives_with_stomach_cancer', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_death_reason', 'patient_id', 'person_neoplasm_cancer_status', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'progression_determined_by', 'radiation_therapy', 'reflux_history', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_STAD_mutation', '_GENOMIC_ID_TCGA_STAD_mutation_curated_broad_gene', '_GENOMIC_ID_TCGA_STAD_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_STAD_exp_GA_exon', '_GENOMIC_ID_TCGA_STAD_exp_HiSeqV2', '_GENOMIC_ID_TCGA_STAD_hMethyl27', '_GENOMIC_ID_TCGA_STAD_mutation_bcm_gene', '_GENOMIC_ID_TCGA_STAD_gistic2', '_GENOMIC_ID_TCGA_STAD_hMethyl450', '_GENOMIC_ID_data/public/TCGA/STAD/miRNA_GA_gene', '_GENOMIC_ID_TCGA_STAD_RPPA', '_GENOMIC_ID_TCGA_STAD_miRNA_HiSeq', '_GENOMIC_ID_TCGA_STAD_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_STAD_gistic2thd', '_GENOMIC_ID_TCGA_STAD_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_STAD_exp_HiSeq_exon', '_GENOMIC_ID_TCGA_STAD_exp_GA', '_GENOMIC_ID_TCGA_STAD_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_STAD_mutation_broad_gene', '_GENOMIC_ID_TCGA_STAD_PDMRNAseq', '_GENOMIC_ID_data/public/TCGA/STAD/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_STAD_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_STAD_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_STAD_exp_HiSeq', '_GENOMIC_ID_TCGA_STAD_miRNA_GA']\n" ] } ], "source": [ "# Step 1: Search for directories related to Stomach Cancer\n", "import os\n", "\n", "# List all directories in TCGA root directory\n", "tcga_dirs = os.listdir(tcga_root_dir)\n", "\n", "# Look for stomach cancer datasets\n", "matching_dirs = [dir_name for dir_name in tcga_dirs \n", " if any(term in dir_name.lower() for term in \n", " [\"stomach\", \"gastric\"])]\n", "\n", "if not matching_dirs:\n", " print(f\"No exact matching directory found for trait: {trait}\")\n", " print(f\"Available directories: {tcga_dirs}\")\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(f\"Task marked as completed. {trait} is not directly represented in the TCGA dataset.\")\n", "else:\n", " # If we found matching directories\n", " print(f\"Found matching directories: {matching_dirs}\")\n", " \n", " # Select the appropriate directory for stomach cancer\n", " selected_dir = matching_dirs[0] # Default to first match\n", " if \"TCGA_Stomach_Cancer_(STAD)\" in matching_dirs:\n", " selected_dir = \"TCGA_Stomach_Cancer_(STAD)\" # This is the exact match\n", " \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": "22cccb83", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "abdae9c9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:03:26.684987Z", "iopub.status.busy": "2025-03-25T04:03:26.684868Z", "iopub.status.idle": "2025-03-25T04:03:26.696092Z", "shell.execute_reply": "2025-03-25T04:03:26.695780Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [70.0, 51.0, 51.0, 62.0, 52.0], 'days_to_birth': [nan, nan, -18698.0, -22792.0, -19014.0]}\n", "Gender columns preview:\n", "{'gender': ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']}\n" ] } ], "source": [ "# 1. Identify age and gender columns from clinical data columns\n", "candidate_age_cols = [\n", " 'age_at_initial_pathologic_diagnosis', \n", " 'days_to_birth'\n", "]\n", "\n", "candidate_gender_cols = [\n", " 'gender'\n", "]\n", "\n", "# 2. Extract and preview the candidate columns\n", "# First, we need to load the clinical data\n", "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Stomach_Cancer_(STAD)')\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Try reading with different delimiters with error handling\n", "try:\n", " # First try tab delimiter which is common in TCGA files\n", " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep='\\t')\n", "except Exception as e:\n", " try:\n", " # Try with automatic delimiter detection\n", " clinical_df = pd.read_csv(clinical_file_path, index_col=0, sep=None, engine='python')\n", " except Exception as e:\n", " print(f\"Error reading clinical file: {e}\")\n", " # Create an empty DataFrame if all attempts fail\n", " clinical_df = pd.DataFrame()\n", "\n", "# Extract candidate age columns\n", "if not clinical_df.empty:\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", " # Extract candidate 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 columns preview:\")\n", " print(gender_preview)\n", "else:\n", " print(\"Could not load clinical data file.\")\n" ] }, { "cell_type": "markdown", "id": "59e70bda", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "0d0fef5f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:03:26.697173Z", "iopub.status.busy": "2025-03-25T04:03:26.697071Z", "iopub.status.idle": "2025-03-25T04:03:26.699760Z", "shell.execute_reply": "2025-03-25T04:03:26.699489Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Chosen age column: age_at_initial_pathologic_diagnosis\n", "Age column preview: [70.0, 51.0, 51.0, 62.0, 52.0]\n", "Chosen gender column: gender\n", "Gender column preview: ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']\n" ] } ], "source": [ "# Evaluating the age columns\n", "age_cols = {\n", " 'age_at_initial_pathologic_diagnosis': [70.0, 51.0, 51.0, 62.0, 52.0], \n", " 'days_to_birth': [float('nan'), float('nan'), -18698.0, -22792.0, -19014.0]\n", "}\n", "\n", "# Evaluating the gender columns\n", "gender_cols = {\n", " 'gender': ['MALE', 'MALE', 'FEMALE', 'MALE', 'MALE']\n", "}\n", "\n", "# Selecting columns for demographic information\n", "# For age, 'age_at_initial_pathologic_diagnosis' appears better as it has no missing values in the preview\n", "# and directly represents age in years\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# For gender, there's only one column and it has valid values\n", "gender_col = 'gender'\n", "\n", "# Print chosen columns\n", "print(f\"Chosen age column: {age_col}\")\n", "print(f\"Age column preview: {age_cols[age_col]}\")\n", "print(f\"Chosen gender column: {gender_col}\")\n", "print(f\"Gender column preview: {gender_cols[gender_col]}\")\n" ] }, { "cell_type": "markdown", "id": "55d80457", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "0e54ffca", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:03:26.700783Z", "iopub.status.busy": "2025-03-25T04:03:26.700685Z", "iopub.status.idle": "2025-03-25T04:04:11.037220Z", "shell.execute_reply": "2025-03-25T04:04:11.036825Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Saved clinical data with 580 samples\n", "After normalization: 19848 genes remaining\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene expression data\n", "Linked data shape: (450, 19851) (samples x features)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (450, 19851)\n", "For the feature 'Stomach_Cancer', the least common label is '0' with 35 occurrences. This represents 7.78% of the dataset.\n", "The distribution of the feature 'Stomach_Cancer' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 58.0\n", " 50% (Median): 67.0\n", " 75%: 73.0\n", "Min: 30.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 159 occurrences. This represents 35.33% 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/Stomach_Cancer/TCGA.csv\n" ] } ], "source": [ "# Step 1: Extract and standardize clinical features\n", "# Use the Stomach Cancer directory identified in Step 1\n", "selected_dir = \"TCGA_Stomach_Cancer_(STAD)\"\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 stomach cancer patients from TCGA.\"\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 }