{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "bd95fb80", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:53.539113Z", "iopub.status.busy": "2025-03-25T07:31:53.538751Z", "iopub.status.idle": "2025-03-25T07:31:53.706927Z", "shell.execute_reply": "2025-03-25T07:31:53.706542Z" } }, "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 = \"Liver_Cancer\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_Cancer/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_Cancer/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_Cancer/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Liver_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bf463adb", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "78132a46", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:53.708367Z", "iopub.status.busy": "2025-03-25T07:31:53.708222Z", "iopub.status.idle": "2025-03-25T07:31:54.751920Z", "shell.execute_reply": "2025-03-25T07:31:54.751562Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Looking for a relevant cohort directory for Liver_Cancer...\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", "Liver Cancer-related cohorts: ['TCGA_Liver_Cancer_(LIHC)']\n", "Selected cohort: TCGA_Liver_Cancer_(LIHC)\n", "Clinical data file: TCGA.LIHC.sampleMap_LIHC_clinicalMatrix\n", "Genetic data file: TCGA.LIHC.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'adjacent_hepatic_tissue_inflammation_extent_type', 'age_at_initial_pathologic_diagnosis', 'albumin_result_lower_limit', 'albumin_result_specified_value', 'albumin_result_upper_limit', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'bilirubin_lower_limit', 'bilirubin_upper_limit', 'cancer_first_degree_relative', 'child_pugh_classification_grade', 'creatinine_lower_level', 'creatinine_upper_limit', 'creatinine_value_in_mg_dl', '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', 'eastern_cancer_oncology_group', 'fetoprotein_outcome_lower_limit', 'fetoprotein_outcome_upper_limit', 'fetoprotein_outcome_value', 'fibrosis_ishak_score', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'hist_hepato_carc_fact', 'hist_hepato_carcinoma_risk', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'inter_norm_ratio_lower_limit', 'intern_norm_ratio_upper_limit', 'is_ffpe', 'lost_follow_up', 'neoplasm_histologic_grade', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_ablation_embo_tx', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'new_tumor_event_liver_transplant', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'person_neoplasm_cancer_status', 'platelet_result_count', 'platelet_result_lower_limit', 'platelet_result_upper_limit', 'post_op_ablation_embolization_tx', 'postoperative_rx_tx', 'prothrombin_time_result_value', 'radiation_therapy', 'relative_family_cancer_history', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'specimen_collection_method_name', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_bilirubin_upper_limit', 'tumor_tissue_site', 'vascular_tumor_cell_type', 'vial_number', 'viral_hepatitis_serology', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_LIHC_gistic2', '_GENOMIC_ID_TCGA_LIHC_gistic2thd', '_GENOMIC_ID_TCGA_LIHC_mutation_bcm_gene', '_GENOMIC_ID_TCGA_LIHC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_LIHC_PDMRNAseq', '_GENOMIC_ID_TCGA_LIHC_RPPA', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_LIHC_mutation_bcgsc_gene', '_GENOMIC_ID_data/public/TCGA/LIHC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_LIHC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_LIHC_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_LIHC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_LIHC_mutation_broad_gene', '_GENOMIC_ID_TCGA_LIHC_hMethyl450']\n", "\n", "Clinical data shape: (438, 109)\n", "Genetic data shape: (20530, 423)\n" ] } ], "source": [ "import os\n", "\n", "# Check if there's a suitable cohort directory for Liver_Cancer\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", "# Liver Cancer-related keywords\n", "liver_keywords = ['liver', 'hepatic', 'hepatocellular', 'lihc']\n", "\n", "# Look for Liver Cancer-related directories\n", "liver_related_dirs = []\n", "for d in available_dirs:\n", " if any(keyword in d.lower() for keyword in liver_keywords):\n", " liver_related_dirs.append(d)\n", "\n", "print(f\"Liver Cancer-related cohorts: {liver_related_dirs}\")\n", "\n", "if not liver_related_dirs:\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", " # Select the most relevant match for Liver Cancer\n", " # Prioritize directories that mention \"liver\" specifically\n", " liver_specific = [d for d in liver_related_dirs if 'liver' in d.lower()]\n", " if liver_specific:\n", " selected_cohort = liver_specific[0]\n", " else:\n", " # Otherwise select other related cohorts\n", " selected_cohort = liver_related_dirs[0] # Take the first match if multiple exist\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": "75148d73", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "36a7c95b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:54.753770Z", "iopub.status.busy": "2025-03-25T07:31:54.753653Z", "iopub.status.idle": "2025-03-25T07:31:54.763194Z", "shell.execute_reply": "2025-03-25T07:31:54.762866Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age column candidates preview:\n", "{'age_at_initial_pathologic_diagnosis': [nan, 58.0, 51.0, 55.0, 54.0], 'days_to_birth': [nan, -21318.0, -18768.0, -20187.0, -20011.0]}\n", "\n", "Gender column candidates preview:\n", "{'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Find candidate columns for age\n", "candidate_age_cols = [\n", " 'age_at_initial_pathologic_diagnosis',\n", " 'days_to_birth' # Age can be derived from birth information\n", "]\n", "\n", "# Find candidate columns for gender\n", "candidate_gender_cols = [\n", " 'gender'\n", "]\n", "\n", "# Extract and preview the candidate age columns\n", "clinical_data_path, _ = tcga_get_relevant_filepaths(os.path.join(tcga_root_dir, 'TCGA_Liver_Cancer_(LIHC)'))\n", "clinical_df = pd.read_csv(clinical_data_path, index_col=0, sep='\\t')\n", "\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 column candidates preview:\")\n", " print(age_preview)\n", "\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(\"\\nGender column candidates preview:\")\n", " print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "9618bae4", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "422a2eba", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:54.764812Z", "iopub.status.busy": "2025-03-25T07:31:54.764702Z", "iopub.status.idle": "2025-03-25T07:31:54.768244Z", "shell.execute_reply": "2025-03-25T07:31:54.767921Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Chosen age column: age_at_initial_pathologic_diagnosis\n", "Chosen gender column: gender\n" ] } ], "source": [ "# Examine age column candidates\n", "import numpy as np\n", "\n", "age_candidates = {\n", " 'age_at_initial_pathologic_diagnosis': [np.nan, 58.0, 51.0, 55.0, 54.0],\n", " 'days_to_birth': [np.nan, -21318.0, -18768.0, -20187.0, -20011.0]\n", "}\n", "\n", "# Examine gender column candidates\n", "gender_candidates = {\n", " 'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']\n", "}\n", "\n", "# Select appropriate columns for age and gender\n", "age_col = None\n", "gender_col = None\n", "\n", "# Select age column\n", "if age_candidates:\n", " # 'age_at_initial_pathologic_diagnosis' is directly in years and more interpretable\n", " # than 'days_to_birth' which is negative days from birth\n", " if 'age_at_initial_pathologic_diagnosis' in age_candidates:\n", " age_col = 'age_at_initial_pathologic_diagnosis'\n", " elif 'days_to_birth' in age_candidates:\n", " age_col = 'days_to_birth' # Alternative if direct age not available\n", "\n", "# Select gender column\n", "if gender_candidates:\n", " if 'gender' in gender_candidates:\n", " # Check if values are consistent with expected format\n", " values = gender_candidates['gender']\n", " if all(v in ['MALE', 'FEMALE', None, np.nan] or (isinstance(v, str) and v.upper() in ['MALE', 'FEMALE']) for v in values if v is not None and not pd.isna(v)):\n", " gender_col = 'gender'\n", "\n", "# Print chosen columns\n", "print(f\"Chosen age column: {age_col}\")\n", "print(f\"Chosen gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "a19fce10", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "096cf502", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:54.770096Z", "iopub.status.busy": "2025-03-25T07:31:54.769812Z", "iopub.status.idle": "2025-03-25T07:32:40.576018Z", "shell.execute_reply": "2025-03-25T07:32:40.575677Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features (first 5 rows):\n", " Liver_Cancer Age Gender\n", "sampleID \n", "TCGA-2V-A95S-01 1 NaN 1\n", "TCGA-2Y-A9GS-01 1 58.0 1\n", "TCGA-2Y-A9GT-01 1 51.0 1\n", "TCGA-2Y-A9GU-01 1 55.0 0\n", "TCGA-2Y-A9GV-01 1 54.0 0\n", "\n", "Processing gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original gene data shape: (20530, 423)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Attempting to normalize gene symbols...\n", "Gene data shape after normalization: (19848, 423)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to: ../../output/preprocess/Liver_Cancer/gene_data/TCGA.csv\n", "\n", "Linking clinical and genetic data...\n", "Clinical data shape: (438, 3)\n", "Genetic data shape: (19848, 423)\n", "Number of common samples: 423\n", "\n", "Linked data shape: (423, 19851)\n", "Linked data preview (first 5 rows, first few columns):\n", " Liver_Cancer Age Gender A1BG A1BG-AS1\n", "TCGA-ED-A7PX-01 1 48.0 0 1.074326 -1.643783\n", "TCGA-DD-A39Z-11 0 43.0 0 10.811726 3.683017\n", "TCGA-DD-A4NH-01 1 65.0 0 6.408826 0.520517\n", "TCGA-DD-A3A1-11 0 65.0 1 10.839326 3.239417\n", "TCGA-XR-A8TC-01 1 43.0 0 8.524626 0.677917\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Data shape after handling missing values: (423, 19851)\n", "\n", "Checking for bias in features:\n", "For the feature 'Liver_Cancer', the least common label is '0' with 50 occurrences. This represents 11.82% of the dataset.\n", "The distribution of the feature 'Liver_Cancer' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 52.0\n", " 50% (Median): 62.0\n", " 75%: 69.0\n", "Min: 16.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' with 143 occurrences. This represents 33.81% 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/Liver_Cancer/TCGA.csv\n", "Clinical data saved to: ../../output/preprocess/Liver_Cancer/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", "# Use the correct cohort identified in Step 1\n", "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Liver_Cancer_(LIHC)')\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() # Keep original orientation for now\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", " # First check if we need to transpose based on the data format\n", " # In TCGA data, typically genes are rows and samples are columns\n", " if gene_df_for_norm.shape[0] > gene_df_for_norm.shape[1]:\n", " # More rows than columns, likely genes are rows already\n", " normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm)\n", " else:\n", " # Need to transpose first\n", " normalized_gene_df = normalize_gene_symbols_in_index(gene_df_for_norm.T)\n", " \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\n", " normalized_gene_df = genetic_df\n", " \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", "# In TCGA, samples are typically columns in the gene data and index in the clinical 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", " # Try the alternative orientation\n", " common_samples = set(linked_clinical_df.index).intersection(set(normalized_gene_df.index))\n", " print(f\"Checking alternative orientation: {len(common_samples)} common samples found.\")\n", " \n", " if len(common_samples) == 0:\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 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 Liver Cancer cohort used for Liver Cancer gene expression analysis.\"\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 }