{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "a8565ddd", "metadata": {}, "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 = \"Hypothyroidism\"\n", "cohort = \"GSE224330\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Hypothyroidism\"\n", "in_cohort_dir = \"../../input/GEO/Hypothyroidism/GSE224330\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hypothyroidism/GSE224330.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hypothyroidism/gene_data/GSE224330.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hypothyroidism/clinical_data/GSE224330.csv\"\n", "json_path = \"../../output/preprocess/Hypothyroidism/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3ee8728b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "fd8f07f0", "metadata": {}, "outputs": [], "source": [ "from tools.preprocess import *\n", "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Read the matrix file to obtain background information and sample characteristics data\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n", "print(\"Background Information:\")\n", "print(background_info)\n", "print(\"Sample Characteristics Dictionary:\")\n", "print(sample_characteristics_dict)\n" ] }, { "cell_type": "markdown", "id": "77050f68", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "a6399a61", "metadata": {}, "outputs": [], "source": [ "# Analyze the dataset based on the provided information\n", "import numpy as np\n", "import pandas as pd\n", "import os\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on background information, this dataset contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Trait: hypothyroidism (comorbidity row 3)\n", "trait_row = 3\n", "\n", "# Age: available in row 1\n", "age_row = 1\n", "\n", "# Gender: available in row 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait (hypothyroidism) data to binary\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if \"hypothyroidism\" in value.lower():\n", " return 1\n", " elif \"none\" in value.lower() or value.lower() in [\"no\", \"healthy\"]:\n", " return 0\n", " else:\n", " # Other comorbidities not related to hypothyroidism\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Remove the 'y' and convert to integer\n", " if 'y' in value:\n", " try:\n", " return int(value.replace('y', ''))\n", " except ValueError:\n", " return None\n", " else:\n", " try:\n", " return int(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary (0: female, 1: male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if value.lower() == \"female\":\n", " return 0\n", " elif value.lower() == \"male\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability for filtering\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create a sample characteristics dictionary based on the output from previous step\n", " sample_characteristics = {\n", " 0: ['tissue: Isolated monocytes'], \n", " 1: ['age: 63y', 'age: 64y', 'age: 48y', 'age: 70y', 'age: 62y', 'age: 58y', 'age: 57y', 'age: 60y', 'age: 52y', \n", " 'age: 51y', 'age: 53y', 'age: 56y', 'age: 54y', 'age: 61y', 'age: 55y', 'age: 65y', 'age: 84y', 'age: 76y', \n", " 'age: 73y', 'age: 71y', 'age: 59y', 'age: 47y'], \n", " 2: ['gender: female', 'gender: male'], \n", " 3: ['comorbidity: hypothyroidism', 'comorbidity: none', 'comorbidity: osteoporosis', np.nan, \n", " 'comorbidity: schizoaffective disorder\\xa0', 'comorbidity: arthrosis']\n", " }\n", " \n", " # Create a DataFrame representation of the sample characteristics\n", " clinical_data = pd.DataFrame(sample_characteristics)\n", " \n", " # Use the provided function to extract and process clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the selected clinical data\n", " print(\"Preview of selected clinical data:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the selected clinical data to a CSV file\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "7db5b0f0", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "4399c2a0", "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import gzip\n", "import re\n", "\n", "# Function to read GEO series matrix file for clinical data\n", "def parse_geo_series_matrix(file_path):\n", " # Open the gzipped file\n", " with gzip.open(file_path, 'rt') as f:\n", " lines = f.readlines()\n", " \n", " # Extract sample characteristics data\n", " sample_chars = {}\n", " column_names = None\n", " current_row = None\n", " \n", " for line in lines:\n", " line = line.strip()\n", " \n", " # Find the line with sample names (GSM IDs)\n", " if line.startswith('!Sample_geo_accession'):\n", " column_names = line.split('\\t')[1:] # Skip the first element (header)\n", " \n", " # Start capturing sample characteristics\n", " elif line.startswith('!Sample_characteristics_ch'):\n", " current_row = len(sample_chars)\n", " parts = line.split('\\t')\n", " values = parts[1:]\n", " sample_chars[current_row] = values\n", " \n", " # Stop when we reach the data table\n", " elif line.startswith('!series_matrix_table_begin'):\n", " break\n", " \n", " # Convert to DataFrame\n", " if column_names and sample_chars:\n", " df = pd.DataFrame(sample_chars, index=column_names).T\n", " return df\n", " \n", " return None\n", "\n", "# Scan the cohort directory to understand available files\n", "series_matrix_file = os.path.join(in_cohort_dir, \"GSE224330_series_matrix.txt.gz\")\n", "is_gene_available = os.path.exists(series_matrix_file) # Series matrix usually contains gene expression data\n", "\n", "# Parse the series matrix file to extract clinical data\n", "clinical_data = None\n", "if is_gene_available:\n", " clinical_data = parse_geo_series_matrix(series_matrix_file)\n", " if clinical_data is not None:\n", " print(\"Successfully parsed clinical data from series matrix file\")\n", " else:\n", " print(\"Could not parse clinical data from series matrix file\")\n", "else:\n", " print(\"No series matrix file found for gene expression data\")\n", "\n", "# Inspect clinical data to find trait, age, and gender information\n", "sample_chars = {}\n", "if clinical_data is not None:\n", " # Print unique values for each row to help identify trait, age, and gender\n", " print(\"\\nSample characteristics:\")\n", " for i, row in clinical_data.iterrows():\n", " unique_values = row.unique()\n", " sample_chars[i] = unique_values\n", " if len(unique_values) < 10: # Only print if there aren't too many unique values\n", " print(f\"Row {i}: {unique_values}\")\n", "else:\n", " print(\"No clinical data available to analyze\")\n", "\n", "# Now let's identify trait, age, and gender rows and define conversion functions\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Default conversion functions\n", "def convert_trait(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " value_str = str(value).lower()\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " \n", " if any(term in value_str for term in [\"hypothyroidism\", \"hypothyroid\", \"hashimoto\"]):\n", " return 1 # Has hypothyroidism\n", " elif any(term in value_str for term in [\"healthy\", \"control\", \"normal\", \"euthyroid\"]):\n", " return 0 # No hypothyroidism\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " value_str = str(value).lower()\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " \n", " # Try to extract numeric age\n", " age_match = re.search(r'(\\d+(?:\\.\\d+)?)', value_str)\n", " if age_match:\n", " return float(age_match.group(1))\n", " else:\n", " return None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " value_str = str(value).lower()\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " \n", " if any(term in value_str for term in [\"female\", \"f\", \"woman\", \"women\"]):\n", " return 0 # Female\n", " elif any(term in value_str for term in [\"male\", \"m\", \"man\", \"men\"]):\n", " return 1 # Male\n", " else:\n", " return None\n", "\n", "# Check for trait, age, and gender in sample characteristics\n", "if sample_chars:\n", " for row, values in sample_chars.items():\n", " values_str = ' '.join([str(v) for v in values if v is not None])\n", " \n", " # Look for trait information\n", " if trait_row is None and any(term in values_str.lower() for term in \n", " [\"thyroid\", \"disease\", \"diagnosis\", \"status\", \"condition\", \"patient\", \"subject\"]):\n", " trait_row = row\n", " \n", " # Look for age information\n", " if age_row is None and any(term in values_str.lower() for term in [\"age\", \"years\", \"year old\"]):\n", " age_row = row\n", " \n", " # Look for gender information\n", " if gender_row is None and any(term in values_str.lower() for term in [\"gender\", \"sex\", \"male\", \"female\"]):\n", " gender_row = row\n", "\n", "print(f\"\\nIdentified rows - Trait: {trait_row}, Age: {age_row}, Gender: {gender_row}\")\n", "\n", "# Check if we need to refine our search or use more complex matching\n", "if trait_row is None and sample_chars:\n", " print(\"Trait row not identified. Attempting deeper analysis...\")\n", " for row, values in sample_chars.items():\n", " # Check each value in the row to see if it might indicate disease status\n", " has_disease_indicators = False\n", " has_control_indicators = False\n", " \n", " for val in values:\n", " if val is not None:\n", " val_str = str(val).lower()\n", " if any(term in val_str for term in [\"thyroid\", \"hypothyroid\", \"hashimoto\", \"disease\", \"patient\"]):\n", " has_disease_indicators = True\n", " if any(term in val_str for term in [\"healthy\", \"control\", \"normal\"]):\n", " has_control_indicators = True\n", " \n", " if has_disease_indicators or has_control_indicators:\n", " trait_row = row\n", " print(f\"Potential trait row identified at row {row}\")\n", " break\n", "\n", "# Initial validation of dataset\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# Extract clinical features if available\n", "if is_trait_available and clinical_data is not None:\n", " # Create the output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Extract clinical features\n", " selected_clinical_data = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the result\n", " preview = preview_df(selected_clinical_data)\n", " print(\"\\nClinical data preview:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " selected_clinical_data.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(f\"Clinical feature extraction skipped: trait_available={is_trait_available}\")\n" ] }, { "cell_type": "markdown", "id": "f685fc53", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "acb9fb18", "metadata": {}, "outputs": [], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "33fc9cc8", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "3aebcdc8", "metadata": {}, "outputs": [], "source": [ "# Reviewing the gene identifiers\n", "# The gene IDs shown (e.g., 'A_19_P00315452') appear to be Agilent microarray probe IDs,\n", "# not standard human gene symbols (which would look like \"BRCA1\", \"TP53\", etc.)\n", "# These probe IDs need to be mapped to standard gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "7fa8dbe2", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "d62644ff", "metadata": {}, "outputs": [], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "70bc0a09", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "2576c9fb", "metadata": {}, "outputs": [], "source": [ "# 1. Identify which columns in the gene annotation dataframe correspond to the gene expression identifiers\n", "# Looking at the gene expression data, we see identifiers like 'A_19_P00315452'\n", "# In the gene annotation dataframe, the column 'ID' appears to store the probe IDs\n", "\n", "# Looking at the column names in the gene annotation data:\n", "# ['ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'LOCUSLINK_ID', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE', 'SPOT_ID']\n", "\n", "# The 'ID' column stores the probe identifiers, and 'GENE_SYMBOL' stores the gene symbols\n", "# Note: In the gene annotation, the first few rows are control probes without gene symbols\n", "\n", "# 2. Get a gene mapping dataframe\n", "print(\"Creating gene mapping from probe IDs to gene symbols...\")\n", "prob_col = 'ID'\n", "gene_col = 'GENE_SYMBOL'\n", "\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Created mapping with {len(mapping_df)} rows\")\n", "print(\"Sample of mapping data:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression data\n", "print(\"Converting probe-level measurements to gene-level expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Converted to gene expression data with {len(gene_data.index)} unique genes\")\n", "print(\"Sample of gene expression data (first few genes and samples):\")\n", "print(preview_df(gene_data))\n", "\n", "# Verify the data has valid gene symbols\n", "print(f\"First 10 gene symbols in the processed data:\")\n", "print(list(gene_data.index[:10]))\n", "\n", "# Normalize gene symbols in index\n", "print(\"\\nNormalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {len(gene_data.index)} unique genes\")\n", "print(\"First 10 normalized gene symbols:\")\n", "print(list(gene_data.index[:10]))\n", "\n", "# Save the gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "aeeb0fc5", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "86bbf27b", "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "# 1. Load the normalized gene data and clinical data\n", "# Note: Gene data was already normalized and saved in Step 7\n", "print(\"Loading gene expression and clinical data...\")\n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", "\n", "print(f\"Loaded gene data with {len(gene_data.index)} genes and {len(gene_data.columns)} samples\")\n", "print(f\"Loaded clinical data with {len(clinical_data.index)} features and {len(clinical_data.columns)} samples\")\n", "\n", "# Debug: Inspect sample IDs in both datasets\n", "print(\"\\nSample ID format inspection:\")\n", "print(\"Gene data column names sample:\", list(gene_data.columns)[:3])\n", "print(\"Clinical data index sample:\", list(clinical_data.index)[:3])\n", "\n", "# Standardize sample IDs to ensure consistent formatting\n", "print(\"\\nStandardizing sample IDs...\")\n", "gene_data.columns = gene_data.columns.str.strip('\"')\n", "clinical_data.index = clinical_data.index.str.strip('\"')\n", "\n", "# Verify after standardization\n", "print(\"Gene data column names after standardization:\", list(gene_data.columns)[:3])\n", "print(\"Clinical data index after standardization:\", list(clinical_data.index)[:3])\n", "\n", "# 2. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "linked_data = geo_link_clinical_genetic_data(clinical_data, gene_data)\n", "print(f\"Linked data: {linked_data.shape[0]} samples, {linked_data.shape[1]} features\")\n", "print(\"Preview of linked data:\")\n", "print(preview_df(linked_data))\n", "\n", "# 3. Handle missing values in the linked data\n", "print(\"\\nHandling missing values...\")\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"After handling missing values: {linked_data.shape[0]} samples, {linked_data.shape[1]} features\")\n", "\n", "# Check if we have any samples left after handling missing values\n", "if linked_data.shape[0] == 0:\n", " print(\"No samples remaining after handling missing values. Dataset cannot be used.\")\n", " is_biased = True # Set to True to mark dataset as unusable\n", " is_usable = False\n", " \n", " # Add note about the issue\n", " note = \"No samples remaining after handling missing values. The dataset has too many missing values in gene expression data.\"\n", " \n", " # Validate and save cohort info\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True, \n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " print(f\"\\nDataset not usable for {trait} analysis due to excessive missing values. Data not saved.\")\n", "else:\n", " # 4. Determine whether the trait and demographic features are biased\n", " print(\"\\nChecking for bias in trait and demographic features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", " # 5. Final quality validation and save metadata\n", " print(\"\\nPerforming final quality validation...\")\n", " note = \"Successfully linked gene expression and clinical data for Hypothyroidism analysis.\"\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True, \n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", "\n", " # 6. Save the linked data if usable\n", " if is_usable:\n", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save the linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"\\nLinked data saved to {out_data_file}\")\n", " else:\n", " print(f\"\\nDataset not usable for {trait} analysis due to data quality issues. Data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }