{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ebfd26ee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:14:00.610392Z", "iopub.status.busy": "2025-03-25T06:14:00.610217Z", "iopub.status.idle": "2025-03-25T06:14:00.773680Z", "shell.execute_reply": "2025-03-25T06:14:00.773364Z" } }, "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 = \"Polycystic_Ovary_Syndrome\"\n", "\n", "# Input paths\n", "tcga_root_dir = \"../../input/TCGA\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Polycystic_Ovary_Syndrome/TCGA.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Polycystic_Ovary_Syndrome/gene_data/TCGA.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Polycystic_Ovary_Syndrome/clinical_data/TCGA.csv\"\n", "json_path = \"../../output/preprocess/Polycystic_Ovary_Syndrome/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a97029a4", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "92d4ea15", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:14:00.774978Z", "iopub.status.busy": "2025-03-25T06:14:00.774840Z", "iopub.status.idle": "2025-03-25T06:14:01.503097Z", "shell.execute_reply": "2025-03-25T06:14:01.502711Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Looking for a relevant cohort directory for Polycystic_Ovary_Syndrome...\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", "Polycystic Ovary Syndrome-related cohorts: ['TCGA_Ovarian_Cancer_(OV)']\n", "Selected cohort: TCGA_Ovarian_Cancer_(OV)\n", "Clinical data file: TCGA.OV.sampleMap_OV_clinicalMatrix\n", "Genetic data file: TCGA.OV.sampleMap_HiSeqV2_PANCAN.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Clinical data columns:\n", "['_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mirna_OV', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'anatomic_neoplasm_subdivision', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'clinical_stage', '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', '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_pathologic_diagnosis_method', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'karnofsky_performance_score', 'longest_dimension', 'lost_follow_up', 'lymphatic_invasion', 'neoplasm_histologic_grade', 'new_neoplasm_event_type', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'oct_embedded', 'other_dx', 'pathology_report_file_name', 'patient_id', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'primary_therapy_outcome_success', 'progression_determined_by', 'radiation_therapy', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tumor_residual_disease', 'tumor_tissue_site', 'venous_invasion', 'vial_number', 'vital_status', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_OV_PDMRNAseq', '_GENOMIC_ID_data/public/TCGA/OV/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_OV_mutation_bcm_solid_gene', '_GENOMIC_ID_TCGA_OV_exp_u133a', '_GENOMIC_ID_TCGA_OV_hMethyl450', '_GENOMIC_ID_TCGA_OV_miRNA_HiSeq', '_GENOMIC_ID_TCGA_OV_mutation_curated_bcm_solid_gene', '_GENOMIC_ID_TCGA_OV_hMethyl27', '_GENOMIC_ID_TCGA_OV_mutation_wustl_hiseq_gene', '_GENOMIC_ID_TCGA_OV_RPPA_RBN', '_GENOMIC_ID_TCGA_OV_mutation_wustl_gene', '_GENOMIC_ID_TCGA_OV_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_OV_gistic2thd', '_GENOMIC_ID_TCGA_OV_PDMarray', '_GENOMIC_ID_TCGA_OV_RPPA', '_GENOMIC_ID_TCGA_OV_exp_HiSeq', '_GENOMIC_ID_TCGA_OV_gistic2', '_GENOMIC_ID_TCGA_OV_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_OV_exp_HiSeq_exon', '_GENOMIC_ID_TCGA_OV_exp_HiSeqV2', '_GENOMIC_ID_TCGA_OV_mutation_broad_gene', '_GENOMIC_ID_TCGA_OV_PDMarrayCNV', '_GENOMIC_ID_TCGA_OV_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_OV_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_OV_mutation', '_GENOMIC_ID_TCGA_OV_G4502A_07_3', '_GENOMIC_ID_TCGA_OV_G4502A_07_2']\n", "\n", "Clinical data shape: (630, 101)\n", "Genetic data shape: (20530, 308)\n" ] } ], "source": [ "import os\n", "\n", "# Check if there's a suitable cohort directory for Polycystic Ovary Syndrome\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", "# Polycystic Ovary Syndrome-related keywords\n", "pcos_keywords = ['ovary', 'ovarian', 'polycystic', 'endocrine', 'hormonal', 'reproductive']\n", "\n", "# Look for PCOS-related directories\n", "pcos_related_dirs = []\n", "for d in available_dirs:\n", " if any(keyword in d.lower() for keyword in pcos_keywords):\n", " pcos_related_dirs.append(d)\n", "\n", "print(f\"Polycystic Ovary Syndrome-related cohorts: {pcos_related_dirs}\")\n", "\n", "if not pcos_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 PCOS\n", " # Prioritize directories that mention \"ovary\" or \"ovarian\" specifically\n", " ovarian_specific = [d for d in pcos_related_dirs if 'ovary' in d.lower() or 'ovarian' in d.lower()]\n", " if ovarian_specific:\n", " selected_cohort = ovarian_specific[0]\n", " else:\n", " # Otherwise select other related cohorts\n", " selected_cohort = pcos_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": "5006d81f", "metadata": {}, "source": [ "### Step 2: Find Candidate Demographic Features" ] }, { "cell_type": "code", "execution_count": 3, "id": "becdf6f8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:14:01.505035Z", "iopub.status.busy": "2025-03-25T06:14:01.504875Z", "iopub.status.idle": "2025-03-25T06:14:01.517193Z", "shell.execute_reply": "2025-03-25T06:14:01.516901Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Age columns preview:\n", "{'age_at_initial_pathologic_diagnosis': [nan, nan, nan, nan, nan], 'days_to_birth': [nan, nan, nan, nan, nan]}\n", "Gender columns preview:\n", "{'gender': [nan, nan, nan, nan, nan]}\n" ] } ], "source": [ "# Identify columns that may contain age information\n", "candidate_age_cols = [\n", " 'age_at_initial_pathologic_diagnosis',\n", " 'days_to_birth'\n", "]\n", "\n", "# Identify columns that may contain gender information\n", "candidate_gender_cols = [\n", " 'gender'\n", "]\n", "\n", "# Import libraries\n", "import pandas as pd\n", "import os\n", "\n", "# Get the relevant file paths\n", "cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Ovarian_Cancer_(OV)')\n", "clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\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 columns\n", "if candidate_age_cols:\n", " age_df = clinical_df[candidate_age_cols]\n", " print(\"Age columns preview:\")\n", " print(preview_df(age_df))\n", "\n", "# Extract and preview gender columns\n", "if candidate_gender_cols:\n", " gender_df = clinical_df[candidate_gender_cols]\n", " print(\"Gender columns preview:\")\n", " print(preview_df(gender_df))\n" ] }, { "cell_type": "markdown", "id": "1ef1a16e", "metadata": {}, "source": [ "### Step 3: Select Demographic Features" ] }, { "cell_type": "code", "execution_count": 4, "id": "d531a417", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:14:01.518943Z", "iopub.status.busy": "2025-03-25T06:14:01.518808Z", "iopub.status.idle": "2025-03-25T06:14:01.523549Z", "shell.execute_reply": "2025-03-25T06:14:01.523282Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining age columns:\n", "Column: age_at_initial_pathologic_diagnosis\n", " Non-null values: 607/630 (96.35%)\n", " First 5 values: [nan, nan, nan, nan, nan]\n", " Data type: float64\n", "\n", "Column: days_to_birth\n", " Non-null values: 596/630 (94.60%)\n", " First 5 values: [nan, nan, nan, nan, nan]\n", " Data type: float64\n", "\n", "Examining gender columns:\n", "Column: gender\n", " Non-null values: 607/630 (96.35%)\n", " First 5 values: [nan, nan, nan, nan, nan]\n", " Data type: object\n", "\n", "Chosen age column: age_at_initial_pathologic_diagnosis\n", "Chosen gender column: gender\n" ] } ], "source": [ "# Step: Select Demographic Features\n", "\n", "# Analyze the age columns\n", "print(\"Examining age columns:\")\n", "age_columns = ['age_at_initial_pathologic_diagnosis', 'days_to_birth']\n", "for col in age_columns:\n", " if col in clinical_df.columns:\n", " non_null_count = clinical_df[col].count()\n", " total_count = len(clinical_df)\n", " null_percentage = (1 - non_null_count/total_count) * 100\n", " print(f\"Column: {col}\")\n", " print(f\" Non-null values: {non_null_count}/{total_count} ({100-null_percentage:.2f}%)\")\n", " print(f\" First 5 values: {clinical_df[col].head().tolist()}\")\n", " print(f\" Data type: {clinical_df[col].dtype}\")\n", " print()\n", "\n", "# Analyze the gender columns\n", "print(\"Examining gender columns:\")\n", "gender_columns = ['gender']\n", "for col in gender_columns:\n", " if col in clinical_df.columns:\n", " non_null_count = clinical_df[col].count()\n", " total_count = len(clinical_df)\n", " null_percentage = (1 - non_null_count/total_count) * 100\n", " print(f\"Column: {col}\")\n", " print(f\" Non-null values: {non_null_count}/{total_count} ({100-null_percentage:.2f}%)\")\n", " print(f\" First 5 values: {clinical_df[col].head().tolist()}\")\n", " print(f\" Data type: {clinical_df[col].dtype}\")\n", " print()\n", "\n", "# Based on preview, select appropriate columns\n", "# If all values are NaN or column doesn't exist, set to None\n", "age_col = None\n", "gender_col = None\n", "\n", "# Check if any age column has non-null values\n", "for col in age_columns:\n", " if col in clinical_df.columns and clinical_df[col].notna().any():\n", " age_col = col\n", " break\n", "\n", "# Check if any gender column has non-null values\n", "for col in gender_columns:\n", " if col in clinical_df.columns and clinical_df[col].notna().any():\n", " gender_col = col\n", " break\n", "\n", "# Print the chosen columns\n", "print(f\"Chosen age column: {age_col}\")\n", "print(f\"Chosen gender column: {gender_col}\")\n" ] }, { "cell_type": "markdown", "id": "64dc393d", "metadata": {}, "source": [ "### Step 4: Feature Engineering and Validation" ] }, { "cell_type": "code", "execution_count": 5, "id": "dfc3060b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:14:01.525218Z", "iopub.status.busy": "2025-03-25T06:14:01.525119Z", "iopub.status.idle": "2025-03-25T06:14:17.161322Z", "shell.execute_reply": "2025-03-25T06:14:17.160675Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features (first 5 rows):\n", " Polycystic_Ovary_Syndrome Age Gender\n", "sampleID \n", "TCGA-01-0628-11 0 NaN NaN\n", "TCGA-01-0629-11 0 NaN NaN\n", "TCGA-01-0630-11 0 NaN NaN\n", "TCGA-01-0631-11 0 NaN NaN\n", "TCGA-01-0633-11 0 NaN NaN\n", "\n", "Processing gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Original gene data shape: (20530, 308)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Attempting to normalize gene symbols...\n", "Gene data shape after normalization: (19848, 308)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to: ../../output/preprocess/Polycystic_Ovary_Syndrome/gene_data/TCGA.csv\n", "\n", "Linking clinical and genetic data...\n", "Clinical data shape: (630, 3)\n", "Genetic data shape: (19848, 308)\n", "Number of common samples: 308\n", "\n", "Linked data shape: (308, 19851)\n", "Linked data preview (first 5 rows, first few columns):\n", " Polycystic_Ovary_Syndrome Age Gender A1BG A1BG-AS1\n", "TCGA-29-1697-01 1 62.0 0.0 -2.262674 -2.161383\n", "TCGA-25-1630-01 1 73.0 0.0 0.459726 0.180017\n", "TCGA-29-A5NZ-01 1 66.0 0.0 -1.364574 -0.924383\n", "TCGA-61-1725-01 1 40.0 0.0 0.844026 -0.155883\n", "TCGA-61-2008-02 1 40.0 0.0 -0.700074 -1.640683\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Data shape after handling missing values: (308, 19851)\n", "\n", "Checking for bias in features:\n", "Quartiles for 'Polycystic_Ovary_Syndrome':\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 'Polycystic_Ovary_Syndrome' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 51.0\n", " 50% (Median): 58.0\n", " 75%: 67.0\n", "Min: 30.0\n", "Max: 87.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 308 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Performing final validation...\n", "The dataset was determined to be unusable for this trait. No data files were saved.\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_Ovarian_Cancer_(OV)')\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 Ovarian Cancer cohort used for Polycystic Ovary Syndrome 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 }