{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "f0ac9aa4", "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 = \"Chronic_obstructive_pulmonary_disease_(COPD)\"\n", "cohort = \"GSE210272\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)\"\n", "in_cohort_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE210272\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/GSE210272.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE210272.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE210272.csv\"\n", "json_path = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "0341d526", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "4d9b39e6", "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": "6c07e2b2", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "9e3cc748", "metadata": {}, "outputs": [], "source": [ "```python\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains mRNA expression profiled using Affymetrix Human Gene 1.0 ST Arrays,\n", "# which indicates 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", "\n", "# For COPD trait:\n", "# Looking at the sample characteristics, we can infer COPD from FEV1 % predicted values in index 4.\n", "# In COPD diagnosis, FEV1 % predicted < 80% is often used as a criterion, with lower values indicating more severe COPD.\n", "# The values range from 15% to 69%, suggesting these are patients with varying degrees of COPD severity.\n", "trait_row = 4\n", "\n", "# For age:\n", "# Age data is available at index 2\n", "age_row = 2\n", "\n", "# For gender:\n", "# Gender data is available at index 1\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert FEV1 % predicted values to binary COPD classification.\n", " FEV1 < 50% indicates severe/very severe COPD (1), while FEV1 ≥ 50% indicates mild/moderate COPD (0).\"\"\"\n", " if value is None or \":\" not in value:\n", " return None\n", " try:\n", " fev1_value = float(value.split(\":\")[1].strip())\n", " # Using 50% as a cutoff for severe COPD (1) vs. less severe COPD (0)\n", " return 1 if fev1_value < 50 else 0\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age string to float.\"\"\"\n", " if value is None or \":\" not in value:\n", " return None\n", " try:\n", " return float(value.split(\":\")[1].strip())\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender string to binary (0 for Female, 1 for Male).\"\"\"\n", " if value is None or \":\" not in value:\n", " return None\n", " gender = value.split(\":\")[1].strip().lower()\n", " if \"female\" in gender:\n", " return 0\n", " elif \"male\" in gender:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n", "\n", "# 4. Clinical Feature Extraction\n", "# Since trait_row is not None, we proceed with clinical feature extraction\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary\n", " # First, we need to create this dictionary as it's shown in the previous output\n", " sample_char_dict = {\n", " 0: ['original geo accession: GSM912197', 'original geo accession: GSM912198', 'original geo accession: GSM912199', 'original geo accession: GSM912200', 'original geo accession: GSM912201', 'original geo accession: GSM912202', 'original geo accession: GSM912203', 'original geo accession: GSM912204', 'original geo accession: GSM912205', 'original geo accession: GSM912206', 'original geo accession: GSM912207', 'original geo accession: GSM912208', 'original geo accession: GSM912209', 'original geo accession: GSM912210', 'original geo accession: GSM912211', 'original geo accession: GSM912212', 'original geo accession: GSM912213', 'original geo accession: GSM912214', 'original geo accession: GSM912215', 'original geo accession: GSM912216', 'original geo accession: GSM912217', 'original geo accession: GSM912218', 'original geo accession: GSM912219', 'original geo accession: GSM912220', 'original geo accession: GSM912221', 'original geo accession: GSM912222', 'original geo accession: GSM912223', 'original geo accession: GSM912224', 'original geo accession: GSM912225', 'original geo accession: GSM912226'],\n", " 1: ['Sex: Male', 'Sex: Female'],\n", " 2: ['age: 57.6', 'age: 61', 'age: 66.3', 'age: 71.5', 'age: 63.4', 'age: 50.3', 'age: 60.3', 'age: 66.6', 'age: 57', 'age: 68.9', 'age: 59.2', 'age: 66.9', 'age: 51.9', 'age: 63.7', 'age: 67.2', 'age: 62.3', 'age: 59.1', 'age: 66.2', 'age: 56.6', 'age: 65.1', 'age: 63.3', 'age: 61.3', 'age: 71.4', 'age: 60.4', 'age: 73.2', 'age: 67.8', 'age: 71.2', 'age: 62.7', 'age: 72.4', 'age: 68.8'],\n", " 3: ['smoking status: Current smoker', 'smoking status: Former smoker'],\n", " 4: ['fev1 % predicted: 15', 'fev1 % predicted: 20', 'fev1 % predicted: 31', 'fev1 % predicted: 35', 'fev1 % predicted: 37', 'fev1 % predicted: 38', 'fev1 % predicted: 39', 'fev1 % predicted: 40', 'fev1 % predicted: 41', 'fev1 % predicted: 45', 'fev1 % predicted: 46', 'fev1 % predicted: 48', 'fev1 % predicted: 49', 'fev1 % predicted: 50', 'fev1 % predicted: 51', 'fev1 % predicted: 52', 'fev1 % predicted: 54', 'fev1 % predicted: 55', 'fev1 % predicted: 57', 'fev1 % predicted: 58', 'fev1 % predicted: 59', 'fev1 % predicted: 61', 'fev1 % predicted: 62', 'fev1 % predicted: 63', 'fev1 % predicted: 64', 'fev1 % predicted: 65', 'fev1 % predicted: 66', 'fev1 % predicted: 67', 'fev1 % predicted: 68', 'fev1 % predicted: 69'],\n", " 5: ['cancer status: NA']\n", " }\n", " \n", " # Convert this dictionary to a DataFrame format that can be used with geo_select_clinical_features\n", " # Create a DataFrame with the sample characteristics\n", " clinical_data = pd.DataFrame(sample_char_dict)\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", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\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 to CSV\n", " selected_clinical_df.to\n" ] }, { "cell_type": "markdown", "id": "b2375a02", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "41bef54c", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import json\n", "import os\n", "import re\n", "from typing import Optional, Dict, Any, Callable\n", "\n", "# Load clinical data\n", "input_files = os.listdir(in_cohort_dir)\n", "clinical_data_file = None\n", "for file in input_files:\n", " if file.endswith('_sample_characteristics.txt'):\n", " clinical_data_file = os.path.join(in_cohort_dir, file)\n", " break\n", "\n", "if clinical_data_file:\n", " clinical_data = pd.read_csv(clinical_data_file, sep='\\t')\n", " print(\"Sample characteristics loaded.\")\n", " print(f\"Shape: {clinical_data.shape}\")\n", " sample_char_dict = clinical_data.to_dict(orient='list')\n", " unique_values = {key: list(set(val)) for key, val in sample_char_dict.items() if key != 'Sample'}\n", " print(\"Unique values in each column:\")\n", " for key, values in unique_values.items():\n", " print(f\"{key}: {values}\")\n", "else:\n", " print(\"No sample characteristics file found.\")\n", " sample_char_dict = {}\n", " unique_values = {}\n", "\n", "# Let's check if gene expression data is likely available\n", "is_gene_available = True # Default assumption for GEO datasets unless clear evidence suggests otherwise\n", "\n", "# Function to extract value from cell content\n", "def extract_value(cell):\n", " if isinstance(cell, str) and ':' in cell:\n", " return cell.split(':', 1)[1].strip()\n", " return cell\n", "\n", "# Analyze what rows contain trait, age, and gender information\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Check available rows in sample characteristics\n", "for row_id, values in unique_values.items():\n", " for value in values:\n", " if isinstance(value, str):\n", " value_lower = value.lower()\n", " \n", " # Check for COPD information\n", " if 'copd' in value_lower or 'chronic obstructive pulmonary disease' in value_lower:\n", " trait_row = row_id\n", " \n", " # Check for age information\n", " elif 'age' in value_lower:\n", " age_row = row_id\n", " \n", " # Check for gender/sex information\n", " elif 'gender' in value_lower or 'sex' in value_lower:\n", " gender_row = row_id\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " \n", " value = extract_value(value)\n", " if not value:\n", " return None\n", " \n", " value_lower = value.lower()\n", " if 'copd' in value_lower or 'yes' in value_lower or 'patient' in value_lower:\n", " return 1\n", " elif 'control' in value_lower or 'no' in value_lower or 'healthy' in value_lower:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if value is None:\n", " return None\n", " \n", " value = extract_value(value)\n", " if not value:\n", " return None\n", " \n", " # Try to extract a number from the value\n", " age_match = re.search(r'(\\d+(?:\\.\\d+)?)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " else:\n", " return None\n", "\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " \n", " value = extract_value(value)\n", " if not value:\n", " return None\n", " \n", " value_lower = value.lower()\n", " if 'female' in value_lower or 'f' == value_lower:\n", " return 0\n", " elif 'male' in value_lower or 'm' == value_lower:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Check if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Save metadata\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", "# If clinical data is available, extract and save it\n", "if is_trait_available:\n", " selected_clinical = 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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the extracted clinical data\n", " preview = preview_df(selected_clinical)\n", " print(\"Clinical data preview:\")\n", " print(preview)\n", " \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", " # Save the clinical data\n", " selected_clinical.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"No trait data available. Skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "f310bd0c", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "dbea8c7e", "metadata": {}, "outputs": [], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "13a03dce", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "4b347536", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers from the previous step\n", "# The identifiers are in the format ENSG00000000003_at, which are Ensembl gene IDs \n", "# (ENSG prefix) with an \"_at\" suffix, not standard human gene symbols\n", "\n", "# Ensembl IDs need to be mapped to human gene symbols for better interpretability\n", "# and consistency with other datasets\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "38c744da", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "96bdafa1", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Let's look for platform information in the SOFT file to understand the annotation better\n", "print(\"\\nSearching for platform information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if '!Series_platform_id' in line:\n", " print(line.strip())\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Platform ID not found in first 100 lines\")\n", " break\n", "\n", "# Check if the SOFT file includes any reference to gene symbols\n", "print(\"\\nSearching for gene symbol information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " gene_symbol_lines = []\n", " for i, line in enumerate(f):\n", " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n", " gene_symbol_lines.append(line.strip())\n", " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n", " break\n", " \n", " if gene_symbol_lines:\n", " print(\"Found references to gene symbols:\")\n", " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n", " print(line)\n", " else:\n", " print(\"No explicit gene symbol references found in first 1000 lines\")\n", "\n", "# Look for alternative annotation files or references in the directory\n", "print(\"\\nChecking for additional annotation files in the directory:\")\n", "all_files = os.listdir(in_cohort_dir)\n", "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n" ] }, { "cell_type": "markdown", "id": "675657fa", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "5329e19a", "metadata": {}, "outputs": [], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene annotation data from the SOFT file\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Extract and process the gene expression data again to ensure it's properly loaded\n", "gene_data = get_genetic_data(matrix_file)\n", "print(f\"Gene data shape: {gene_data.shape}\")\n", "print(f\"Gene data index sample: {gene_data.index[:5].tolist()}\")\n", "\n", "# Create a mapping dataframe with the ID and ORF columns\n", "mapping_df = gene_annotation[['ID', 'ORF']].copy()\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "\n", "# Set the Gene column to be the Ensembl IDs (from ORF column)\n", "# These will later be matched against gene_synonym.json during normalization\n", "mapping_df['Gene'] = mapping_df['ORF']\n", "print(\"First few rows of mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# Check the overlap between gene data index and mapping IDs\n", "common_ids = set(mapping_df['ID']) & set(gene_data.index)\n", "print(f\"Number of IDs in common between mapping and gene data: {len(common_ids)}\")\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", "# 3. Apply gene mapping to convert probe-level data to gene expression data\n", "try:\n", " # Apply the mapping to convert probe IDs to gene symbols and aggregate\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " print(f\"Gene expression data converted to gene symbols. Shape: {gene_data.shape}\")\n", " \n", " # Save the processed gene data\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Gene expression data saved to {out_gene_data_file}\")\n", " \n", " # Preview the gene data\n", " print(\"\\nPreview of gene expression data:\")\n", " print(gene_data.head())\n", "except Exception as e:\n", " print(f\"Error applying gene mapping: {e}\")\n", " import traceback\n", " traceback.print_exc()\n", " \n", " # As a fallback, save the original gene data\n", " print(\"Saving original gene data as fallback\")\n", " gene_data.to_csv(out_gene_data_file)\n" ] }, { "cell_type": "markdown", "id": "81df72fe", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "e9579d8e", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data \n", "# (This was already done in the previous step, so no need to repeat)\n", "print(f\"Normalized gene data shape: {gene_data.shape}\")\n", "\n", "# 2. Examine the sample IDs in the gene expression data to understand the structure\n", "print(\"Gene data column names (sample IDs):\")\n", "print(gene_data.columns[:5]) # Print first 5 for brevity\n", "\n", "# Inspect the clinical data format from the matrix file directly\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "print(\"\\nRaw clinical data structure:\")\n", "print(f\"Clinical data shape: {clinical_data.shape}\")\n", "print(f\"Clinical data columns: {clinical_data.columns[:5]}\")\n", "\n", "# Get the sample characteristics to re-extract the disease information\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(\"\\nSample characteristics dictionary:\")\n", "print(sample_characteristics_dict)\n", "\n", "# 3. Directly create clinical features from the raw data again\n", "# Verify trait row contains the disease information (OA vs RA)\n", "print(\"\\nValues in trait row:\")\n", "trait_values = clinical_data.iloc[trait_row].values\n", "print(trait_values[:5])\n", "\n", "# Create clinical dataframe with proper structure\n", "# First get the sample IDs from gene data as these are our actual sample identifiers\n", "sample_ids = gene_data.columns.tolist()\n", "\n", "# Create the clinical features dataframe with those sample IDs\n", "clinical_features = pd.DataFrame(index=[trait], columns=sample_ids)\n", "\n", "# Fill the clinical features with our trait values by mapping GSM IDs to actual values\n", "for col in clinical_data.columns:\n", " if col in sample_ids:\n", " # Extract the disease value and convert it\n", " disease_val = clinical_data.iloc[trait_row][col]\n", " clinical_features.loc[trait, col] = convert_trait(disease_val)\n", "\n", "print(\"\\nCreated clinical features dataframe:\")\n", "print(f\"Shape: {clinical_features.shape}\")\n", "print(clinical_features.iloc[:, :5]) # Show first 5 columns\n", "\n", "# 4. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", "print(f\"\\nLinked data shape before handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Handle missing values - we need to use the actual column name, not the trait variable\n", "# First identify the actual trait column name in the linked data\n", "trait_column = clinical_features.index[0] # This should be 'Osteoarthritis'\n", "print(f\"Actual trait column in linked data: {trait_column}\")\n", "\n", "# Now handle missing values with the correct column name\n", "linked_data_clean = handle_missing_values(linked_data, trait_column)\n", "print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n", "\n", "# 6. Evaluate bias in trait and demographic features\n", "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait_column)\n", "\n", "# 7. Conduct final quality validation\n", "note = \"Dataset contains gene expression data from synovial fibroblasts of RA and OA patients. Data includes high serum and low serum responses.\"\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=(linked_data_clean.shape[0] > 0),\n", " is_biased=is_biased,\n", " df=linked_data_clean,\n", " note=note\n", ")\n", "\n", "# 8. Save linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_clean.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable due to quality issues - linked data not saved\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }