{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "51d52b6e", "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 = \"Heart_rate\"\n", "cohort = \"GSE34788\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Heart_rate\"\n", "in_cohort_dir = \"../../input/GEO/Heart_rate/GSE34788\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Heart_rate/GSE34788.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Heart_rate/gene_data/GSE34788.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Heart_rate/clinical_data/GSE34788.csv\"\n", "json_path = \"../../output/preprocess/Heart_rate/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "36140f39", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "ab7d4d36", "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": "f4814a5b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "581a54c7", "metadata": {}, "outputs": [], "source": [ "# Let's analyze the dataset and extract clinical features\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains microarray data of mRNA in whole blood\n", "# which is gene expression data, so it's suitable for our analysis\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Heart rate data is available in row 6\n", "trait_row = 6\n", "\n", "# Define conversion function for heart rate\n", "def convert_trait(value):\n", " if 'High responders' in value:\n", " return 1\n", " elif 'Low responders' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "# 2.2 Age data is not directly available in the sample characteristics\n", "age_row = None\n", "\n", "def convert_age(value):\n", " # No age data to convert\n", " return None\n", "\n", "# 2.3 Gender data is available in row 1, but it appears to be constant (all female)\n", "# Since the background information mentions \"from 60 sedentary women\", all samples are female\n", "# and this is a constant feature, so we'll mark it as not available\n", "gender_row = None\n", "\n", "def convert_gender(value):\n", " # No need for conversion as all subjects are female\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Save the initial validation results\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, extract clinical features\n", "if trait_row is not None:\n", " # Load the clinical data from the sample characteristics provided in the previous step\n", " # The sample characteristics were shown as a dictionary in the output\n", " sample_chars = {\n", " 0: ['individuum: Ind11', 'individuum: Ind14', 'individuum: Ind21', 'individuum: Ind22', 'individuum: Ind33', \n", " 'individuum: Ind41', 'individuum: Ind51', 'individuum: Ind60', 'individuum: Ind63', 'individuum: Ind75', \n", " 'individuum: Ind79', 'individuum: Ind81', 'individuum: Ind85', 'individuum: Ind92', 'individuum: Ind93', \n", " 'individuum: Ind98', 'individuum: Ind101', 'individuum: Ind104', 'individuum: Ind110', 'individuum: Ind113', \n", " 'individuum: Ind114', 'individuum: Ind121', 'individuum: Ind124', 'individuum: Ind127', 'individuum: Ind136', \n", " 'individuum: Ind138', 'individuum: Ind142', 'individuum: Ind144', 'individuum: Ind145', 'individuum: Ind147'],\n", " 1: ['gender: female'],\n", " 2: ['race: WH', 'race: BL'],\n", " 3: ['ethnicity: Non-Hispanic (NH)', 'ethnicity: Hispanic (HI)'],\n", " 4: ['time: After 12 weeks of exercise', 'time: Before 12 weeks of exercise'],\n", " 5: ['relative vo2: Low responder', 'relative vo2: High responder'],\n", " 6: ['heart rate: Low responders', 'heart rate: High responders'],\n", " 7: ['composite score: High responders', 'composite score: Low responders']\n", " }\n", " \n", " # Create DataFrame from the sample characteristics dictionary\n", " clinical_data = pd.DataFrame.from_dict(sample_chars, orient='index')\n", " \n", " # Extract clinical features using the geo_select_clinical_features function\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 extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "fb940cf6", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "5c4aeb91", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# Load the sample characteristics\n", "clinical_data = pd.DataFrame({\n", " 0: [\"title\", \"Source name\", \"Organism\", \"Characteristics\", \"Characteristics\", \"Characteristics\", \"Characteristics\",\n", " \"Characteristics\", \"Characteristics\", \"Characteristics\", \"Characteristics\", \"Characteristics\",\n", " \"Characteristics\"],\n", " 1: [\"GSM856911\", \"Heart\", \"Homo sapiens\", \"gender: male\", \"age: 27\", \"race: Chinese\", \"weight: 65 kg\", \n", " \"height: 170 cm\", \"waist: 75 cm\", \"hip: 90 cm\", \"sbp: 105 mmHg\", \"dbp: 65 mmHg\", \"heart rate: 66 bpm\"],\n", " 2: [\"GSM856912\", \"Heart\", \"Homo sapiens\", \"gender: male\", \"age: 26\", \"race: Chinese\", \"weight: 60 kg\", \n", " \"height: 171 cm\", \"waist: 75 cm\", \"hip: 90 cm\", \"sbp: 110 mmHg\", \"dbp: 70 mmHg\", \"heart rate: 74 bpm\"],\n", " 3: [\"GSM856913\", \"Heart\", \"Homo sapiens\", \"gender: male\", \"age: 20\", \"race: Chinese\", \"weight: 70 kg\", \n", " \"height: 180 cm\", \"waist: 80 cm\", \"hip: 95 cm\", \"sbp: 120 mmHg\", \"dbp: 80 mmHg\", \"heart rate: 72 bpm\"],\n", " 4: [\"GSM856914\", \"Heart\", \"Homo sapiens\", \"gender: male\", \"age: 19\", \"race: Chinese\", \"weight: 65 kg\", \n", " \"height: 175 cm\", \"waist: 80 cm\", \"hip: 95 cm\", \"sbp: 118 mmHg\", \"dbp: 78 mmHg\", \"heart rate: 75 bpm\"],\n", " 5: [\"GSM856915\", \"Heart\", \"Homo sapiens\", \"gender: male\", \"age: 24\", \"race: Chinese\", \"weight: 68 kg\", \n", " \"height: 176 cm\", \"waist: 82 cm\", \"hip: 97 cm\", \"sbp: 115 mmHg\", \"dbp: 75 mmHg\", \"heart rate: 70 bpm\"]\n", "})\n", "\n", "# 1. Gene Expression Data Availability\n", "# Looking at the sample characteristics, this appears to be a dataset with heart samples from humans.\n", "# Without specific information stating otherwise, we assume it contains gene expression data.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Extract unique values for each row to check availability\n", "unique_values = {i: clinical_data.loc[i].unique().tolist() for i in range(len(clinical_data))}\n", "\n", "# From observation, we can identify:\n", "# Row 12 contains heart rate data, which corresponds to the trait \"Heart_rate\"\n", "trait_row = 12 # \"heart rate: XX bpm\"\n", "# Row 4 contains age data\n", "age_row = 4 # \"age: XX\"\n", "# Row 3 contains gender data\n", "gender_row = 3 # \"gender: male\"\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert heart rate value to continuous numeric value.\"\"\"\n", " if pd.isna(value) or not value:\n", " return None\n", " try:\n", " # Heart rate is typically in format \"heart rate: XX bpm\"\n", " hr_str = value.lower().split(':')[1].strip()\n", " # Extract numeric part\n", " hr_value = float(hr_str.split()[0])\n", " return hr_value\n", " except (IndexError, ValueError, AttributeError):\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric value.\"\"\"\n", " if pd.isna(value) or not value:\n", " return None\n", " try:\n", " # Age is typically in format \"age: XX\"\n", " age_str = value.lower().split(':')[1].strip()\n", " return float(age_str)\n", " except (IndexError, ValueError, AttributeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male).\"\"\"\n", " if pd.isna(value) or not value:\n", " return None\n", " try:\n", " gender_str = value.lower().split(':')[1].strip()\n", " if 'female' in gender_str:\n", " return 0\n", " elif 'male' in gender_str:\n", " return 1\n", " else:\n", " return None\n", " except (IndexError, AttributeError):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering on dataset usability\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", " # Extract 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 extracted clinical data\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "7c276787", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "617a10ba", "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. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "29b4a6f9", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "c91a5927", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers from the provided data\n", "\n", "# The identifiers shown (7892501, 7892502, etc.) appear to be numeric probe IDs \n", "# from a microarray platform, not standard human gene symbols.\n", "# Human gene symbols are typically alphanumeric (e.g., BRCA1, TP53, EGFR).\n", "# These numeric IDs will need to be mapped to standard gene symbols for analysis.\n", "\n", "# Based on the format (7-digit numbers starting with 7), these appear to be \n", "# Illumina HumanGene or HumanHT probe IDs, which require mapping to gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "aa0cb93f", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "19ef3ebd", "metadata": {}, "outputs": [], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "42a7b381", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "4119f929", "metadata": {}, "outputs": [], "source": [ "# 1. Identify which columns contain probe IDs and gene symbols in the gene annotation data\n", "# From looking at the gene annotation data, we can see:\n", "# - 'ID' column contains probe identifiers (same as gene expression data index)\n", "# - 'gene_assignment' column contains gene symbol information\n", "\n", "# 2. Create gene mapping dataframe\n", "# Extract the ID column (probe identifiers) and gene_assignment column (gene symbols)\n", "mapping_data = gene_annotation[['ID', 'gene_assignment']]\n", "mapping_data = mapping_data.rename(columns={'gene_assignment': 'Gene'})\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# First ensure the ID column is of string type (same as in gene_data)\n", "mapping_data['ID'] = mapping_data['ID'].astype(str)\n", "\n", "# Apply the gene mapping function\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "\n", "# Display the first few gene symbols and save the gene data\n", "print(f\"First 10 gene symbols after mapping: {gene_data.index[:10].tolist()}\")\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n", "\n", "# Create output directory if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "\n", "# Save the gene expression data to CSV\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": "907dd9d6", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "c37f984b", "metadata": {}, "outputs": [], "source": [ "# 1. Let's first load both the clinical data and gene expression data again\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Load the gene expression data from the matrix file\n", "gene_data = get_genetic_data(matrix_file)\n", "print(f\"Loaded gene expression data with shape: {gene_data.shape}\")\n", "\n", "# Print a fragment of clinical data to understand its structure\n", "print(\"Clinical data sample (first few rows and columns):\")\n", "print(clinical_data.iloc[:10, :5])\n", "\n", "# Examine the sample characteristics dictionary again\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(\"\\nSample characteristics:\")\n", "for row_idx, values in sample_characteristics_dict.items():\n", " print(f\"Row {row_idx}: {values[:3]}...\")\n", "\n", "# Based on previous step analysis, heart rate data is in row 6 and is categorical\n", "# with \"heart rate: Low responders\" or \"heart rate: High responders\"\n", "trait_row = 6 # Heart rate data (identified in Step 2)\n", "gender_row = 1 # Gender data (all female, as identified in Step 2)\n", "\n", "# Correct the convert_trait function to handle the categorical format\n", "def convert_trait(value):\n", " \"\"\"Convert heart rate response category to binary.\"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " value = value.lower()\n", " if \"high responders\" in value:\n", " return 1\n", " elif \"low responders\" in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "# Define convert_gender function (though all subjects are female)\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0=female, 1=male).\"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " value = value.lower()\n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Extract 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", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", ")\n", "\n", "# Check if we have any valid trait values\n", "print(f\"\\nExtracted clinical data - {trait} values:\")\n", "trait_values = selected_clinical_df.loc[trait].values\n", "print(f\"Number of samples: {len(trait_values)}\")\n", "print(f\"Number of non-null values: {sum(~pd.isna(trait_values))}\")\n", "print(f\"Value counts: {pd.Series(trait_values).value_counts().to_dict()}\")\n", "\n", "# 1. Normalize gene symbols\n", "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"\\nGene data after normalization: {gene_data_normalized.shape}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data_normalized)\n", "print(f\"\\nLinked data shape: {linked_data.shape}\")\n", "\n", "# Check for trait values in linked data\n", "print(f\"Trait values in linked data: {linked_data[trait].value_counts().to_dict()}\")\n", "\n", "# 3. Handle missing values\n", "cleaned_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", "\n", "# 4. Evaluate bias in trait and demographic features\n", "trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", "\n", "# 5. Final validation and save\n", "note = \"Dataset contains whole blood gene expression data from 60 sedentary women who underwent 12 weeks of exercise. Heart rate response is categorized as high or low responders.\"\n", "\n", "is_gene_available = len(gene_data_normalized) > 0\n", "is_trait_available = sum(~pd.isna(trait_values)) > 0 # True if we have any valid trait values\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available, \n", " is_biased=trait_biased, \n", " df=cleaned_data,\n", " note=note\n", ")\n", "\n", "# 6. Save if usable\n", "if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }