{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "02edf4cb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:39.576041Z", "iopub.status.busy": "2025-03-25T05:55:39.575917Z", "iopub.status.idle": "2025-03-25T05:55:39.740700Z", "shell.execute_reply": "2025-03-25T05:55:39.740316Z" } }, "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 = \"Obesity\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obesity/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obesity/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obesity/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Obesity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "5b7b3c9a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "f3772884", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:39.742238Z", "iopub.status.busy": "2025-03-25T05:55:39.742089Z", "iopub.status.idle": "2025-03-25T05:55:40.777149Z", "shell.execute_reply": "2025-03-25T05:55:40.776763Z" } }, "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", "No direct obesity term found, using obesity-associated cancer type: TCGA_Liver_Cancer_(LIHC)\n", "Selected directory: TCGA_Liver_Cancer_(LIHC)\n", "Clinical data file: ../../input/TCGA/TCGA_Liver_Cancer_(LIHC)/TCGA.LIHC.sampleMap_LIHC_clinicalMatrix\n", "Genetic data file: ../../input/TCGA/TCGA_Liver_Cancer_(LIHC)/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", "# Step 1: Look for directories related to Obesity\n", "tcga_subdirs = os.listdir(tcga_root_dir)\n", "print(f\"Available TCGA subdirectories: {tcga_subdirs}\")\n", "\n", "# Look for directories related to Obesity\n", "target_dir = None\n", "obesity_related_terms = [\"Obesity\", \"BMI\", \"Body Mass\", \"Fat\", \"Adipose\", \"Metabolic\"]\n", "\n", "for subdir in tcga_subdirs:\n", " for term in obesity_related_terms:\n", " if term.lower() in subdir.lower():\n", " target_dir = subdir\n", " break\n", " if target_dir:\n", " break\n", "\n", "# If no direct match, consider selecting a cancer type known to be associated with obesity\n", "if target_dir is None:\n", " obesity_associated_cancers = [\n", " \"TCGA_Liver_Cancer_(LIHC)\", # Liver cancer has strong associations with obesity\n", " \"TCGA_Pancreatic_Cancer_(PAAD)\", # Pancreatic cancer associated with obesity\n", " \"TCGA_Endometrioid_Cancer_(UCEC)\", # Endometrial cancer associated with obesity\n", " \"TCGA_Colon_Cancer_(COAD)\" # Colorectal cancer associated with obesity\n", " ]\n", " \n", " for cancer in obesity_associated_cancers:\n", " if cancer in tcga_subdirs:\n", " target_dir = cancer\n", " print(f\"No direct obesity term found, using obesity-associated cancer type: {target_dir}\")\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": "8f06f57e", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "94614db6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:40.778522Z", "iopub.status.busy": "2025-03-25T05:55:40.778402Z", "iopub.status.idle": "2025-03-25T05:55:40.787973Z", "shell.execute_reply": "2025-03-25T05:55:40.787657Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns 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 columns preview:\n", "{'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n" ] } ], "source": [ "# Identify candidate columns for age\n", "candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n", "\n", "# Identify candidate columns for gender\n", "candidate_gender_cols = ['gender']\n", "\n", "# Read clinical data\n", "clinical_data_file = '../../input/TCGA/TCGA_Liver_Cancer_(LIHC)/TCGA.LIHC.sampleMap_LIHC_clinicalMatrix'\n", "clinical_df = pd.read_csv(clinical_data_file, 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", "\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", "\n", "print(\"Age columns preview:\")\n", "print(age_preview)\n", "print(\"\\nGender columns preview:\")\n", "print(gender_preview)\n" ] }, { "cell_type": "markdown", "id": "74f672f5", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "22c2db86", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:40.789235Z", "iopub.status.busy": "2025-03-25T05:55:40.789118Z", "iopub.status.idle": "2025-03-25T05:55:40.791618Z", "shell.execute_reply": "2025-03-25T05:55:40.791289Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected age column: age_at_initial_pathologic_diagnosis\n", "Selected gender column: gender\n" ] } ], "source": [ "# Inspect the age columns\n", "age_col = None\n", "gender_col = None\n", "\n", "# For age column selection:\n", "# Check 'age_at_initial_pathologic_diagnosis' - has some numeric values but first value is NaN\n", "# Check 'days_to_birth' - has negative values representing days since birth (age in days), also with first value as NaN\n", "# Since both columns have one NaN value but otherwise contain usable information,\n", "# choose 'age_at_initial_pathologic_diagnosis' as it's already in years format (more convenient)\n", "age_col = 'age_at_initial_pathologic_diagnosis'\n", "\n", "# For gender column selection:\n", "# 'gender' column looks good with valid values of 'MALE' and 'FEMALE'\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": "f58687be", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "5bfd210e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:40.792922Z", "iopub.status.busy": "2025-03-25T05:55:40.792803Z", "iopub.status.idle": "2025-03-25T05:56:20.823890Z", "shell.execute_reply": "2025-03-25T05:56:20.822820Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Checking for obesity-related features in clinical data:\n", "Found: followup_case_report_form_submission_reason\n", "sampleID\n", "TCGA-2V-A95S-01 NaN\n", "TCGA-2Y-A9GS-01 NaN\n", "TCGA-2Y-A9GT-01 NaN\n", "TCGA-2Y-A9GU-01 NaN\n", "TCGA-2Y-A9GV-01 NaN\n", "Name: followup_case_report_form_submission_reason, dtype: object\n", "\n", "Found: height\n", "sampleID\n", "TCGA-2V-A95S-01 173.0\n", "TCGA-2Y-A9GS-01 162.0\n", "TCGA-2Y-A9GT-01 182.0\n", "TCGA-2Y-A9GU-01 154.0\n", "TCGA-2Y-A9GV-01 167.0\n", "Name: height, dtype: float64\n", "\n", "Found: initial_weight\n", "sampleID\n", "TCGA-2V-A95S-01 170.0\n", "TCGA-2Y-A9GS-01 80.0\n", "TCGA-2Y-A9GT-01 NaN\n", "TCGA-2Y-A9GU-01 120.0\n", "TCGA-2Y-A9GV-01 NaN\n", "Name: initial_weight, dtype: float64\n", "\n", "Found: weight\n", "sampleID\n", "TCGA-2V-A95S-01 78.0\n", "TCGA-2Y-A9GS-01 92.0\n", "TCGA-2Y-A9GT-01 122.0\n", "TCGA-2Y-A9GU-01 78.0\n", "TCGA-2Y-A9GV-01 85.0\n", "Name: weight, dtype: float64\n", "\n", "BMI calculated and Obesity classification created\n", "Clinical data saved to ../../output/preprocess/Obesity/clinical_data/TCGA.csv\n", "Clinical data shape: (438, 3)\n", " Obesity 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" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Obesity/gene_data/TCGA.csv\n", "Normalized gene data shape: (19848, 423)\n", "Linked data shape: (423, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values - linked data shape: (423, 19851)\n", "For the feature 'Obesity', the least common label is '0' with 50 occurrences. This represents 11.82% of the dataset.\n", "The distribution of the feature 'Obesity' 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", "After removing biased features - linked data shape: (423, 19851)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Obesity/TCGA.csv\n" ] } ], "source": [ "# Step 1: Extract and standardize the clinical features\n", "# Get file paths\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 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", "# Check for obesity-related features in clinical data\n", "print(\"Checking for obesity-related features in clinical data:\")\n", "for col in clinical_df.columns:\n", " if any(term in col.lower() for term in ['weight', 'height', 'bmi', 'body', 'mass']):\n", " print(f\"Found: {col}\")\n", " # Preview the first few values\n", " print(clinical_df[col].head())\n", " print()\n", "\n", "# Create BMI column if height and weight are available\n", "if 'height' in clinical_df.columns and 'weight' in clinical_df.columns:\n", " # Convert to numeric, handle potential errors\n", " clinical_df['height_num'] = pd.to_numeric(clinical_df['height'], errors='coerce')\n", " clinical_df['weight_num'] = pd.to_numeric(clinical_df['weight'], errors='coerce')\n", " \n", " # Calculate BMI: weight(kg) / height(m)²\n", " # Assuming height is in cm, convert to meters\n", " clinical_df['BMI'] = clinical_df['weight_num'] / ((clinical_df['height_num']/100) ** 2)\n", " \n", " # Classify obesity based on BMI\n", " def classify_obesity(bmi):\n", " if pd.isna(bmi):\n", " return None\n", " elif bmi >= 30:\n", " return 1 # Obese\n", " else:\n", " return 0 # Not obese\n", " \n", " clinical_df['Obesity'] = clinical_df['BMI'].apply(classify_obesity)\n", " print(\"BMI calculated and Obesity classification created\")\n", "else:\n", " # If we don't have both height and weight, check if we have just weight\n", " if 'weight' in clinical_df.columns:\n", " # Use weight as a proxy, assuming higher weights are more likely to indicate obesity\n", " clinical_df['weight_num'] = pd.to_numeric(clinical_df['weight'], errors='coerce')\n", " \n", " # Get threshold for obesity (e.g., top 30% of weights could be considered obese)\n", " weight_threshold = clinical_df['weight_num'].quantile(0.7)\n", " \n", " def classify_by_weight(weight):\n", " if pd.isna(weight):\n", " return None\n", " elif weight >= weight_threshold:\n", " return 1 # Likely obese\n", " else:\n", " return 0 # Likely not obese\n", " \n", " clinical_df['Obesity'] = clinical_df['weight_num'].apply(classify_by_weight)\n", " print(f\"Used weight with threshold {weight_threshold} as proxy for obesity classification\")\n", " else:\n", " print(\"No obesity-related features found. Using tumor/normal classification as a substitute.\")\n", " # If no obesity data, create a placeholder trait based on sample types\n", " # In TCGA, tumor samples are 01-09, normal samples are 10-19\n", " clinical_df['Obesity'] = clinical_df.index.map(tcga_convert_trait)\n", "\n", "# Create standardized clinical features dataframe with trait, age, and gender\n", "clinical_features = tcga_select_clinical_features(\n", " clinical_df, \n", " trait=trait, # Using predefined trait variable\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=trait)\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=trait)\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 Obesity, Age, Gender\n", "is_trait_available = trait in linked_data.columns\n", "\n", "# Take notes of special findings\n", "notes = f\"TCGA Liver Cancer dataset used for {trait} analysis. \"\n", "if 'BMI' in clinical_df.columns:\n", " notes += f\"BMI data was calculated from height and weight and used for {trait} classification.\"\n", "elif 'weight' in clinical_df.columns:\n", " notes += f\"Weight was used as a proxy for {trait} classification.\"\n", "else:\n", " notes += f\"No direct {trait} data available; used tumor vs normal classification as substitute.\"\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 }