{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "63ab535e", "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 = \"Lupus_(Systemic_Lupus_Erythematosus)\"\n", "cohort = \"GSE180393\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)\"\n", "in_cohort_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)/GSE180393\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/GSE180393.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/gene_data/GSE180393.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/clinical_data/GSE180393.csv\"\n", "json_path = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "250c4a79", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "81ec5d3e", "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": "9b5a9a71", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "e7a0e7e6", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from microarrays\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# The sample characteristics dictionary shows sample groups that include Lupus Nephritis (LN) cases \n", "# and various other kidney conditions including living donors (controls)\n", "trait_row = 0 # The disease information is in row 0\n", "\n", "# Unfortunately, there is no age information in the sample characteristics\n", "age_row = None\n", "\n", "# No gender information available\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert sample group information to binary trait values (Lupus vs non-Lupus)\"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " # Extract the value after the colon and strip whitespace\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 1 for Lupus cases, 0 for non-Lupus\n", " if 'LN-WHO' in value: # LN = Lupus Nephritis\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age information - not available in this dataset\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender information - not available in this dataset\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata - Initial validation\n", "# Trait data is available since trait_row is not None\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", "# 4. Clinical Feature Extraction\n", "# Since trait_row is not None, we extract clinical features\n", "# Create a DataFrame from the sample characteristics dictionary\n", "sample_chars_dict = {0: ['sample group: Living donor', 'sample group: infection-associated GN', 'sample group: FSGS', 'sample group: LN-WHO III', 'sample group: LN-WHO IV', 'sample group: DN', 'sample group: amyloidosis', 'sample group: Membrano-Proliferative GN', 'sample group: MN', 'sample group: AKI', 'sample group: LN-WHO V', 'sample group: FGGS', \"sample group: 2'FSGS\", 'sample group: Thin-BMD', 'sample group: Immuncomplex GN', 'sample group: LN-WHO-V', 'sample group: IgAN', 'sample group: LN-WHO IV+V', 'sample group: LN-WHO III+V', 'sample group: LN-WHO-I/II', 'sample group: chronic Glomerulonephritis (GN) with infiltration by CLL', 'sample group: CKD with mod-severe Interstitial fibrosis', 'sample group: Fibrillary GN', 'sample group: Interstitial nephritis', 'sample group: Hypertensive Nephrosclerosis', 'sample group: Unaffected parts of Tumor Nephrectomy'], 1: ['tissue: Glomeruli from kidney biopsy']}\n", "\n", "# Convert the dictionary to a DataFrame directly\n", "clinical_data = pd.DataFrame(sample_chars_dict)\n", "\n", "# Use geo_select_clinical_features as intended\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 data\n", "preview_result = preview_df(selected_clinical_df)\n", "print(\"Preview of selected clinical features:\")\n", "print(preview_result)\n", "\n", "# Create the 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\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": "1e5f3f09", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "eda049fc", "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# Step 1: Load data for analysis\n", "# Let's first look for any data files in the cohort directory\n", "gene_files = []\n", "meta_files = []\n", "for file in os.listdir(in_cohort_dir):\n", " file_path = os.path.join(in_cohort_dir, file)\n", " if file.endswith('.txt') or file.endswith('.csv'):\n", " if 'matrix' in file.lower() or 'expression' in file.lower() or 'gene' in file.lower():\n", " gene_files.append(file_path)\n", " elif 'meta' in file.lower() or 'clinical' in file.lower() or 'phenotype' in file.lower():\n", " meta_files.append(file_path)\n", "\n", "# Let's examine the series matrix file to understand the dataset structure\n", "if len(gene_files) > 0:\n", " try:\n", " with open(gene_files[0], 'r') as f:\n", " header_lines = [next(f) for _ in range(50)] # Read first 50 lines to understand the file structure\n", " \n", " # Check if there's gene expression data\n", " is_gene_available = any('gene' in line.lower() for line in header_lines) and not any(\n", " 'mirna' in line.lower() and not 'gene' in line.lower() for line in header_lines)\n", " except:\n", " is_gene_available = False\n", "else:\n", " is_gene_available = False\n", "\n", "# Load clinical data if available\n", "if len(meta_files) > 0:\n", " try:\n", " clinical_data = pd.read_csv(meta_files[0], sep='\\t')\n", " \n", " # Look at the structure to identify sample characteristics\n", " # Convert to string to handle non-string data\n", " clinical_data_str = clinical_data.astype(str)\n", " \n", " # Create a dictionary of unique values for each row\n", " sample_chars = {}\n", " for i, row in clinical_data_str.iterrows():\n", " values = row.values\n", " if len(values) > 1: # Ensure there's actual data\n", " # Skip rows with all identical values (not useful for our analysis)\n", " if len(set(values[1:])) > 1: # More than one unique value (excluding the first column which is usually a label)\n", " sample_chars[i] = list(set(values[1:]))\n", " \n", " # Print sample characteristics to understand the data\n", " print(\"Sample Characteristics:\")\n", " for row_idx, unique_vals in sample_chars.items():\n", " print(f\"Row {row_idx}: {clinical_data.iloc[row_idx, 0]}\")\n", " print(f\" Unique values: {unique_vals[:5]}{' ...' if len(unique_vals) > 5 else ''}\")\n", " print()\n", " \n", " # Data from row 9 contains diagnosis information (SLE vs. healthy)\n", " # Data from row 8 contains age information\n", " # Data from row 7 contains gender information\n", " \n", " # 2.1 Identify rows for trait, age, and gender\n", " trait_row = 9 # Row with diagnosis information\n", " age_row = 8 # Row with age information\n", " gender_row = 7 # Row with gender information\n", " \n", " # 2.2 Define conversion functions\n", " def convert_trait(value):\n", " \"\"\"Convert trait information to binary (0 for healthy, 1 for SLE)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value_str = str(value).lower()\n", " if ':' in value_str:\n", " value_str = value_str.split(':', 1)[1].strip()\n", " \n", " if 'sle' in value_str or 'lupus' in value_str or 'patient' in value_str:\n", " return 1\n", " elif 'healthy' in value_str or 'control' in value_str or 'hc' in value_str:\n", " return 0\n", " return None\n", " \n", " def convert_age(value):\n", " \"\"\"Convert age information to continuous value\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value_str = str(value).lower()\n", " if ':' in value_str:\n", " value_str = value_str.split(':', 1)[1].strip()\n", " \n", " # Extract number from string (age often reported as \"age: XX years\")\n", " import re\n", " age_match = re.search(r'(\\d+(\\.\\d+)?)', value_str)\n", " if age_match:\n", " return float(age_match.group(1))\n", " return None\n", " \n", " def convert_gender(value):\n", " \"\"\"Convert gender information to binary (0 for female, 1 for male)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value_str = str(value).lower()\n", " if ':' in value_str:\n", " value_str = value_str.split(':', 1)[1].strip()\n", " \n", " if 'female' in value_str or 'f' == value_str.strip():\n", " return 0\n", " elif 'male' in value_str or 'm' == value_str.strip():\n", " return 1\n", " return None\n", " \n", " # Check if trait data is available (not all values are the same)\n", " is_trait_available = trait_row is not None\n", " \n", " except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " is_trait_available = False\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", "else:\n", " is_trait_available = False\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", "\n", "# 3. 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", "# 4. Extract clinical features if available\n", "if trait_row is not None:\n", " # Ensure the output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Extract clinical features\n", " clinical_features = 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 features\n", " preview = preview_df(clinical_features)\n", " print(\"Preview of clinical features:\")\n", " for col, values in preview.items():\n", " print(f\"{col}: {values}\")\n", " \n", " # Save clinical data to CSV\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "d2918426", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "feaaf707", "metadata": {}, "outputs": [], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "0d5c008f", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "f5784b99", "metadata": {}, "outputs": [], "source": [ "# Looking at the gene identifiers, I notice they follow the format of a RefSeq ID with \"_at\" suffix\n", "# This is characteristic of Affymetrix microarray probe identifiers, not standard human gene symbols\n", "# These would need to be mapped to human gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "795d2313", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "4638b8dd", "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. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "5e0e12fa", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "de02c835", "metadata": {}, "outputs": [], "source": [ "# 1. First, extract gene annotation data from the SOFT file\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Load the gene expression data that was extracted in Step 4\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# Examine columns in gene annotation to find appropriate ones for mapping\n", "print(\"Column names in gene annotation:\")\n", "print(gene_annotation.columns.tolist())\n", "\n", "# Check for a column that might contain gene symbols\n", "gene_symbol_columns = [col for col in gene_annotation.columns if 'symbol' in col.lower() or 'gene_symbol' in col.lower()]\n", "print(f\"Potential gene symbol columns: {gene_symbol_columns}\")\n", "\n", "# Check for columns with gene information\n", "gene_info_columns = [col for col in gene_annotation.columns \n", " if any(term in col.lower() for term in ['gene', 'symbol', 'name', 'description'])]\n", "print(f\"Columns with gene information: {gene_info_columns}\")\n", "\n", "# Examine more columns to find gene symbols\n", "if len(gene_info_columns) > 0:\n", " for col in gene_info_columns:\n", " print(f\"\\nSample values from column '{col}':\")\n", " print(gene_annotation[col].head())\n", "\n", "# Determine which columns to use for probe-to-gene mapping\n", "if 'GENE_SYMBOL' in gene_annotation.columns:\n", " prob_col = 'ID'\n", " gene_col = 'GENE_SYMBOL'\n", "elif any('gene_symbol' in col.lower() for col in gene_annotation.columns):\n", " prob_col = 'ID'\n", " gene_col = next(col for col in gene_annotation.columns if 'gene_symbol' in col.lower())\n", "else:\n", " # If there's no explicit gene symbol column, we can try using GENE_NAME or similar\n", " potential_cols = [col for col in gene_annotation.columns \n", " if any(term in col.lower() for term in ['gene_name', 'symbol', 'description'])]\n", " \n", " if potential_cols:\n", " prob_col = 'ID'\n", " gene_col = potential_cols[0]\n", " else:\n", " # As a fallback, we'll use ENTREZ_GENE_ID\n", " prob_col = 'ID'\n", " gene_col = 'ENTREZ_GENE_ID'\n", "\n", "print(f\"\\nUsing columns for mapping: Probe={prob_col}, Gene={gene_col}\")\n", "\n", "# Create the mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(\"\\nGene mapping dataframe preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# Convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(\"\\nConverted gene expression data preview:\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "if len(gene_data) > 0:\n", " print(f\"First few gene symbols: {gene_data.index[:5].tolist()}\")\n", " print(f\"Number of samples: {len(gene_data.columns)}\")\n", " \n", "# If we used Entrez IDs, provide appropriate notice\n", "if gene_col == 'ENTREZ_GENE_ID':\n", " print(\"\\nNote: Using Entrez Gene IDs as gene identifiers. Further conversion to gene symbols may be needed.\")\n" ] }, { "cell_type": "markdown", "id": "42e02f0e", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "2e908480", "metadata": {}, "outputs": [], "source": [ "# 1. First check what happened with clinical data\n", "print(\"Checking clinical data file existence:\", os.path.exists(out_clinical_data_file))\n", "\n", "# Try to properly save the clinical data first\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "\n", "# Since we don't have valid clinical data from previous steps, we need to recreate it\n", "# Get the clinical data from the soft/matrix file\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", "# Extract the relevant information for a binary trait: Lupus vs non-Lupus\n", "def convert_trait(value):\n", " \"\"\"Convert sample group information to binary trait values (Lupus vs non-Lupus)\"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " # Extract the value after the colon and strip whitespace\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 1 for Lupus cases, 0 for non-Lupus\n", " if 'LN-WHO' in value: # LN = Lupus Nephritis\n", " return 1\n", " else:\n", " return 0\n", "\n", "# Create a simplified clinical feature dataframe with just the trait\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0, # The disease info is in the first row based on our earlier analysis\n", " convert_trait=convert_trait,\n", " age_row=None, # No age data available\n", " convert_age=None,\n", " gender_row=None, # No gender data available\n", " convert_gender=None\n", ")\n", "\n", "# Save the clinical data\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Created and saved clinical data to {out_clinical_data_file}\")\n", "\n", "# 2. Get the raw gene expression data\n", "gene_data_raw = get_genetic_data(matrix_file)\n", "print(f\"Raw genetic data shape: {gene_data_raw.shape}\")\n", "\n", "# Extract gene annotation data\n", "gene_annotation = get_gene_annotation(soft_file)\n", "print(f\"Gene annotation shape: {gene_annotation.shape}\")\n", "\n", "# Since we have Entrez IDs, we need to map them to gene symbols\n", "# Create a mapping from IDs to their corresponding gene symbols\n", "gene_mapping = pd.DataFrame()\n", "gene_mapping['ID'] = gene_annotation['ID']\n", "gene_mapping['Gene'] = gene_annotation['ENTREZ_GENE_ID'].astype(str) # Convert to string\n", "\n", "# Filter to remove any entries with missing/NaN gene IDs\n", "gene_mapping = gene_mapping.dropna()\n", "print(f\"Gene mapping shape after cleanup: {gene_mapping.shape}\")\n", "\n", "# Show some examples of the mapping\n", "print(f\"Example gene mappings: {gene_mapping.head()}\")\n", "\n", "# Apply gene mapping - simplified approach treating Entrez IDs as gene identifiers\n", "gene_data = apply_gene_mapping(gene_data_raw, gene_mapping)\n", "\n", "# Check if we have valid data after mapping\n", "print(f\"Gene data after mapping - shape: {gene_data.shape}\")\n", "print(f\"Gene index samples: {gene_data.index[:5].tolist() if len(gene_data) > 0 else 'Empty'}\")\n", "\n", "# Create directory for gene data file if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "\n", "# Save the gene data - even if it's problematic, for reference\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Saved gene data to {out_gene_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "if len(gene_data) > 0:\n", " # Transpose gene data to have samples as rows\n", " gene_data_t = gene_data.T\n", " \n", " # Load the selected clinical data\n", " clinical_df = selected_clinical_df.T\n", " \n", " # Make sure sample naming is consistent\n", " # Some processing to ensure sample IDs match between datasets\n", " print(f\"Clinical data index: {clinical_df.index[:5]}\")\n", " print(f\"Gene data index: {gene_data_t.index[:5]}\")\n", " \n", " # Check for common samples\n", " common_samples = set(clinical_df.index).intersection(set(gene_data_t.index))\n", " print(f\"Number of common samples between datasets: {len(common_samples)}\")\n", " \n", " # Link the data, keeping only common samples\n", " linked_data = pd.concat([clinical_df, gene_data_t], axis=1)\n", " print(f\"Shape of linked data: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Shape of linked data after handling missing values: {linked_data.shape}\")\n", " \n", " # 5. Check for bias in the dataset\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # 6. Validate and save cohort information\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=len(gene_data) > 0,\n", " is_trait_available=True,\n", " is_biased=is_trait_biased,\n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from kidney biopsies. Gene symbols mapped from Entrez IDs.\"\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", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", " else:\n", " print(\"Dataset validation failed. Data not saved.\")\n", "else:\n", " # If we have no gene data, mark the dataset as not usable\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=False,\n", " is_trait_available=True,\n", " is_biased=None,\n", " df=pd.DataFrame(),\n", " note=\"Failed to map gene identifiers to gene symbols. Dataset cannot be used.\"\n", " )\n", " print(\"No gene data available. Dataset marked as unusable.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }