{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "07d9a0fa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:49:48.491960Z", "iopub.status.busy": "2025-03-25T06:49:48.491720Z", "iopub.status.idle": "2025-03-25T06:49:48.661618Z", "shell.execute_reply": "2025-03-25T06:49:48.661174Z" } }, "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 = \"Atrial_Fibrillation\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Atrial_Fibrillation/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Atrial_Fibrillation/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Atrial_Fibrillation/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Atrial_Fibrillation/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "dcce561a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ae0872b1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:49:48.663038Z", "iopub.status.busy": "2025-03-25T06:49:48.662886Z", "iopub.status.idle": "2025-03-25T06:49:50.044139Z", "shell.execute_reply": "2025-03-25T06:49:50.043455Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Looking for a relevant cohort directory for Atrial_Fibrillation...\n", "Available cohorts: ['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", "Cardiac-related cohorts: []\n", "No direct cardiac cohorts found. Looking for possible related cohorts...\n", "Possible related cohorts: ['TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Thymoma_(THYM)']\n", "Selected cohort: TCGA_Lung_Adenocarcinoma_(LUAD)\n", "Clinical data file: TCGA.LUAD.sampleMap_LUAD_clinicalMatrix\n", "Genetic data file: TCGA.LUAD.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['ABSOLUTE_Ploidy', 'ABSOLUTE_Purity', 'AKT1', 'ALK_translocation', 'BRAF', 'CBL', 'CTNNB1', 'Canonical_mut_in_KRAS_EGFR_ALK', 'Cnncl_mt_n_KRAS_EGFR_ALK_RET_ROS1_BRAF_ERBB2_HRAS_NRAS_AKT1_MAP2', 'EGFR', 'ERBB2', 'ERBB4', 'Estimated_allele_fraction_of_a_clonal_varnt_prsnt_t_1_cpy_pr_cll', 'Expression_Subtype', 'HRAS', 'KRAS', 'MAP2K1', 'MET', 'NRAS', 'PIK3CA', 'PTPN11', 'Pathology', 'Pathology_Updated', 'RET_translocation', 'ROS1_translocation', 'STK11', 'WGS_as_of_20120731_0_no_1_yes', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_LUAD', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_LUAD', '_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', 'anatomic_neoplasm_subdivision', 'anatomic_neoplasm_subdivision_other', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', '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', 'disease_code', 'dlco_predictive_percent', 'eastern_cancer_oncology_group', 'egfr_mutation_performed', 'egfr_mutation_result', 'eml4_alk_translocation_method', 'eml4_alk_translocation_performed', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', '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', 'karnofsky_performance_score', 'kras_gene_analysis_performed', 'kras_mutation_found', 'kras_mutation_result', 'location_in_lung_parenchyma', 'longest_dimension', 'lost_follow_up', 'new_neoplasm_event_type', 'new_tumor_event_after_initial_treatment', 'number_pack_years_smoked', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'post_bronchodilator_fev1_fvc_percent', 'post_bronchodilator_fev1_percent', 'pre_bronchodilator_fev1_fvc_percent', 'pre_bronchodilator_fev1_percent', 'primary_therapy_outcome_success', 'progression_determined_by', 'project_code', 'pulmonary_function_test_performed', 'radiation_therapy', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'stopped_smoking_year', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tobacco_smoking_history', 'tobacco_smoking_history_indicator', 'tumor_tissue_site', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', 'year_of_tobacco_smoking_onset', '_GENOMIC_ID_TCGA_LUAD_mutation', '_GENOMIC_ID_TCGA_LUAD_mutation_curated_broad_gene', '_GENOMIC_ID_TCGA_LUAD_PDMarray', '_GENOMIC_ID_TCGA_LUAD_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LUAD_G4502A_07_3', '_GENOMIC_ID_TCGA_LUAD_hMethyl27', '_GENOMIC_ID_data/public/TCGA/LUAD/miRNA_GA_gene', '_GENOMIC_ID_TCGA_LUAD_gistic2', '_GENOMIC_ID_TCGA_LUAD_hMethyl450', '_GENOMIC_ID_TCGA_LUAD_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_LUAD_gistic2thd', '_GENOMIC_ID_TCGA_LUAD_PDMarrayCNV', '_GENOMIC_ID_TCGA_LUAD_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LUAD_miRNA_HiSeq', '_GENOMIC_ID_TCGA_LUAD_RPPA_RBN', '_GENOMIC_ID_TCGA_LUAD_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LUAD_PDMRNAseq', '_GENOMIC_ID_TCGA_LUAD_RPPA', '_GENOMIC_ID_TCGA_LUAD_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_LUAD_mutation_broad_gene', '_GENOMIC_ID_data/public/TCGA/LUAD/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_LUAD_miRNA_GA']\n", "\n", "Clinical data shape: (706, 147)\n", "Genetic data shape: (20530, 576)\n" ] } ], "source": [ "import os\n", "\n", "# Check if there's a suitable cohort directory for Arrhythmia\n", "print(f\"Looking for a relevant cohort directory for {trait}...\")\n", "\n", "# Check available cohorts\n", "available_dirs = os.listdir(tcga_root_dir)\n", "print(f\"Available cohorts: {available_dirs}\")\n", "\n", "# Arrhythmia is a cardiac condition, so we should look for heart/cardiac-related cohorts\n", "cardiac_related_terms = ['heart', 'cardiac', 'cardiovascular', 'thoracic', 'chest']\n", "\n", "# First check for direct heart/cardiac related cohorts\n", "cardiac_related_dirs = [d for d in available_dirs if any(term in d.lower() for term in cardiac_related_terms)]\n", "print(f\"Cardiac-related cohorts: {cardiac_related_dirs}\")\n", "\n", "# If no direct heart-related cohorts, we might need to look at:\n", "# 1. General datasets that might include cardiac data\n", "# 2. Datasets that affect organs near the heart\n", "# 3. Datasets where cardiac function might be measured as part of standard evaluation\n", "if not cardiac_related_dirs:\n", " print(\"No direct cardiac cohorts found. Looking for possible related cohorts...\")\n", " # Lung, thoracic, or chest area studies might include cardiac data\n", " possible_related_cohorts = [d for d in available_dirs \n", " if any(term in d.lower() for term in ['lung', 'thoracic', 'chest', 'thymoma'])]\n", " print(f\"Possible related cohorts: {possible_related_cohorts}\")\n", " \n", " if possible_related_cohorts:\n", " # Lung studies often include cardiac measures\n", " selected_cohort = [d for d in possible_related_cohorts if 'lung' in d.lower()][0] if any('lung' in d.lower() for d in possible_related_cohorts) else possible_related_cohorts[0]\n", " else:\n", " print(f\"No suitable cohort found for {trait}.\")\n", " # Mark the task as completed by recording the unavailability\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", " # Exit the script early since no suitable cohort was found\n", " selected_cohort = None\n", "else:\n", " selected_cohort = cardiac_related_dirs[0]\n", "\n", "if selected_cohort:\n", " print(f\"Selected cohort: {selected_cohort}\")\n", " \n", " # Get the full path to the selected cohort directory\n", " cohort_dir = os.path.join(tcga_root_dir, selected_cohort)\n", " \n", " # Get the clinical and genetic data file paths\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", " # Load the 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", " # Print the column names of the clinical data\n", " print(\"\\nClinical data columns:\")\n", " print(clinical_df.columns.tolist())\n", " \n", " # Basic info about the datasets\n", " print(f\"\\nClinical data shape: {clinical_df.shape}\")\n", " print(f\"Genetic data shape: {genetic_df.shape}\")\n" ] }, { "cell_type": "markdown", "id": "79b71f3b", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "28962c7a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:49:50.046028Z", "iopub.status.busy": "2025-03-25T06:49:50.045904Z", "iopub.status.idle": "2025-03-25T06:49:50.058083Z", "shell.execute_reply": "2025-03-25T06:49:50.057599Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age-related columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [67.0, 67.0, 72.0, 72.0, 77.0], 'days_to_birth': [-24477.0, -24477.0, -26615.0, -26615.0, -28171.0]}\n", "Gender-related columns preview:\n", "{'gender': ['MALE', 'MALE', 'MALE', 'MALE', '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", "# Extract the clinical data paths\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)'))\n", "\n", "# Load the clinical data\n", "clinical_df = pd.read_csv(clinical_file_path, sep=\"\\t\", index_col=0)\n", "\n", "# Extract and preview age-related columns if there are any candidates\n", "if candidate_age_cols:\n", " age_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_age_cols if col in clinical_df.columns}\n", " print(\"Age-related columns preview:\")\n", " print(age_preview)\n", "\n", "# Extract and preview gender-related columns if there are any candidates\n", "if candidate_gender_cols:\n", " gender_preview = {col: clinical_df[col].head(5).tolist() for col in candidate_gender_cols if col in clinical_df.columns}\n", " print(\"Gender-related columns preview:\")\n", " print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "916c08d3", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "d8fbb0b2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:49:50.059710Z", "iopub.status.busy": "2025-03-25T06:49:50.059594Z", "iopub.status.idle": "2025-03-25T06:49:50.063338Z", "shell.execute_reply": "2025-03-25T06:49:50.062874Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Chosen age column: age_at_initial_pathologic_diagnosis\n", "Age column preview: [67.0, 67.0, 72.0, 72.0, 77.0]\n", "Chosen gender column: gender\n", "Gender column preview: ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']\n" ] } ], "source": [ "# Examining the age-related columns\n", "age_col_candidates = {'age_at_initial_pathologic_diagnosis': [67.0, 67.0, 72.0, 72.0, 77.0], \n", " 'days_to_birth': [-24477.0, -24477.0, -26615.0, -26615.0, -28171.0]}\n", "\n", "# Examining the gender-related columns\n", "gender_col_candidates = {'gender': ['MALE', 'MALE', 'MALE', 'MALE', 'FEMALE']}\n", "\n", "# Select suitable columns for age and gender\n", "# For age, 'age_at_initial_pathologic_diagnosis' is preferred as it directly provides age in years\n", "age_col = 'age_at_initial_pathologic_diagnosis' if age_col_candidates else None\n", "\n", "# For gender, check if the gender column contains valid values\n", "gender_col = 'gender' if gender_col_candidates and all(g in ['MALE', 'FEMALE', None] for g in gender_col_candidates.get('gender', [])) else None\n", "\n", "# Print out the chosen columns\n", "print(f\"Chosen age column: {age_col}\")\n", "print(f\"Age column preview: {age_col_candidates.get(age_col, 'N/A')}\")\n", "print(f\"Chosen gender column: {gender_col}\")\n", "print(f\"Gender column preview: {gender_col_candidates.get(gender_col, 'N/A')}\")\n" ] }, { "cell_type": "markdown", "id": "0e65b722", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "9160e8b1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:49:50.064979Z", "iopub.status.busy": "2025-03-25T06:49:50.064868Z", "iopub.status.idle": "2025-03-25T06:50:56.597301Z", "shell.execute_reply": "2025-03-25T06:50:56.596637Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features (first 5 rows):\n", " Atrial_Fibrillation Age Gender\n", "sampleID \n", "TCGA-18-3406-01 1 67.0 1.0\n", "TCGA-18-3406-11 0 67.0 1.0\n", "TCGA-18-3407-01 1 72.0 1.0\n", "TCGA-18-3407-11 0 72.0 1.0\n", "TCGA-18-3408-01 1 77.0 0.0\n", "\n", "Processing gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original gene data shape: (20530, 553)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Attempting to normalize gene symbols...\n", "Gene data shape after normalization: (0, 20530)\n", "WARNING: Gene symbol normalization returned an empty DataFrame.\n", "Using original gene data instead of normalized data.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to: ../../output/preprocess/Atrial_Fibrillation/gene_data/TCGA.csv\n", "\n", "Linking clinical and genetic data...\n", "Clinical data shape: (626, 3)\n", "Genetic data shape: (20530, 553)\n", "Number of common samples: 553\n", "\n", "Linked data shape: (553, 20533)\n", "Linked data preview (first 5 rows, first few columns):\n", " Atrial_Fibrillation Age Gender ARHGEF10L HIF3A\n", "TCGA-77-8008-01 1 68.0 1.0 -0.062192 0.769474\n", "TCGA-77-8007-11 0 68.0 1.0 -0.123192 1.968274\n", "TCGA-66-2768-01 1 57.0 1.0 -0.110092 -0.399426\n", "TCGA-56-7582-11 0 83.0 1.0 -0.050992 2.772874\n", "TCGA-70-6723-01 1 65.0 1.0 -1.873492 -0.483526\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Data shape after handling missing values: (553, 20533)\n", "\n", "Checking for bias in features:\n", "For the feature 'Atrial_Fibrillation', the least common label is '0' with 51 occurrences. This represents 9.22% of the dataset.\n", "The distribution of the feature 'Atrial_Fibrillation' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 62.0\n", " 50% (Median): 68.0\n", " 75%: 73.0\n", "Min: 39.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 144 occurrences. This represents 26.04% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "\n", "Performing final validation...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to: ../../output/preprocess/Atrial_Fibrillation/TCGA.csv\n", "Clinical data saved to: ../../output/preprocess/Atrial_Fibrillation/clinical_data/TCGA.csv\n" ] } ], "source": [ "# 1. Extract and standardize clinical features\n", "# Use tcga_select_clinical_features which will automatically create the trait variable and add age/gender if provided\n", "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)')\n", "clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n", "\n", "# Load the clinical data if not already loaded\n", "clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n", "\n", "linked_clinical_df = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=trait, \n", " age_col=age_col, \n", " gender_col=gender_col\n", ")\n", "\n", "# Print preview of clinical features\n", "print(\"Clinical features (first 5 rows):\")\n", "print(linked_clinical_df.head())\n", "\n", "# 2. Process gene expression data\n", "print(\"\\nProcessing gene expression data...\")\n", "# Load genetic data from the same cohort directory\n", "genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n", "\n", "# Check gene data shape\n", "print(f\"Original gene data shape: {genetic_df.shape}\")\n", "\n", "# Save a version of the gene data before normalization (as a backup)\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "genetic_df.to_csv(out_gene_data_file.replace('.csv', '_original.csv'))\n", "\n", "# We need to transpose genetic data so genes are rows and samples are columns for normalization\n", "gene_df_for_norm = genetic_df.copy().T\n", "\n", "# Try to normalize gene symbols - adding debug output to understand what's happening\n", "print(\"Attempting to normalize gene symbols...\")\n", "try:\n", " normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm)\n", " print(f\"Gene data shape after normalization: {normalized_gene_df.shape}\")\n", " \n", " # Check if normalization returned empty DataFrame\n", " if normalized_gene_df.shape[0] == 0:\n", " print(\"WARNING: Gene symbol normalization returned an empty DataFrame.\")\n", " print(\"Using original gene data instead of normalized data.\")\n", " # Use original data instead - samples as rows, genes as columns\n", " normalized_gene_df = genetic_df\n", " else:\n", " # If normalization worked, transpose back to original orientation\n", " normalized_gene_df = normalized_gene_df.T\n", "except Exception as e:\n", " print(f\"Error during gene symbol normalization: {e}\")\n", " print(\"Using original gene data instead.\")\n", " normalized_gene_df = genetic_df\n", "\n", "# Save gene data\n", "normalized_gene_df.to_csv(out_gene_data_file)\n", "print(f\"Gene data saved to: {out_gene_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "# TCGA data uses the same sample IDs in both datasets\n", "print(\"\\nLinking clinical and genetic data...\")\n", "print(f\"Clinical data shape: {linked_clinical_df.shape}\")\n", "print(f\"Genetic data shape: {normalized_gene_df.shape}\")\n", "\n", "# Find common samples between clinical and genetic data\n", "common_samples = set(linked_clinical_df.index).intersection(set(normalized_gene_df.columns))\n", "print(f\"Number of common samples: {len(common_samples)}\")\n", "\n", "if len(common_samples) == 0:\n", " print(\"ERROR: No common samples found between clinical and genetic data.\")\n", " # Use is_final=False mode which doesn't require df and is_biased\n", " validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=True\n", " )\n", " print(\"The dataset was determined to be unusable for this trait due to no common samples. No data files were saved.\")\n", "else:\n", " # Filter clinical data to only include common samples\n", " linked_clinical_df = linked_clinical_df.loc[list(common_samples)]\n", " \n", " # Create linked data by merging\n", " linked_data = pd.concat([linked_clinical_df, normalized_gene_df[list(common_samples)].T], axis=1)\n", " \n", " print(f\"\\nLinked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first few columns):\")\n", " display_cols = [trait, 'Age', 'Gender'] + list(linked_data.columns[3:5])\n", " print(linked_data[display_cols].head())\n", " \n", " # 4. Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"\\nData shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 5. Check for bias in trait and demographic features\n", " print(\"\\nChecking for bias in features:\")\n", " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # 6. Validate and save cohort info\n", " print(\"\\nPerforming final validation...\")\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=\"TCGA\",\n", " info_path=json_path,\n", " is_gene_available=len(linked_data.columns) > 3, # More than just trait/age/gender columns\n", " is_trait_available=trait in linked_data.columns,\n", " is_biased=is_trait_biased,\n", " df=linked_data,\n", " note=\"Data from TCGA Lung Squamous Cell Carcinoma cohort used as proxy for Arrhythmia-related cardiac gene expression patterns.\"\n", " )\n", " \n", " # 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", " \n", " # Also save clinical data separately\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_columns = [col for col in linked_data.columns if col in [trait, 'Age', 'Gender']]\n", " linked_data[clinical_columns].to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n", " else:\n", " print(\"The dataset was determined to be unusable for this trait. No data files were 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 }