{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "f2e6ece4", "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_kidney_disease\"\n", "cohort = \"GSE66494\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Chronic_kidney_disease\"\n", "in_cohort_dir = \"../../input/GEO/Chronic_kidney_disease/GSE66494\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Chronic_kidney_disease/GSE66494.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Chronic_kidney_disease/gene_data/GSE66494.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE66494.csv\"\n", "json_path = \"../../output/preprocess/Chronic_kidney_disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "dde62e6c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "0ec6b77b", "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": "6e987eb0", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "12c6e161", "metadata": {}, "outputs": [], "source": [ "import os\n", "import json\n", "import pandas as pd\n", "import numpy as np\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# From the background information, we see this dataset contains microarray analysis with renal biopsy specimens\n", "# This suggests gene expression data, not just miRNA or methylation data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking at sample characteristics dictionary:\n", "# Row 3 shows 'disease status: normal kidney' and row 4 shows 'disease status: chronic kidney disease (CKD)'\n", "# which together represent our trait - we'll need to handle both in convert_trait\n", "trait_row = 3 # We'll use row 3 as the primary and handle row 4 in the convert function\n", "\n", "# There's no apparent age information in the sample characteristics\n", "age_row = None\n", "\n", "# There's no apparent gender information in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary (0 for normal, 1 for CKD)\n", " if \"normal\" in str(value).lower():\n", " return 0\n", " elif \"chronic kidney disease\" in str(value).lower() or \"ckd\" in str(value).lower():\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " # Function not needed as age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " # Function not needed as gender data is not available\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 and 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. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # From the sample characteristics, we need to create a proper clinical data DataFrame\n", " # First, let's map out what we know:\n", " # Row 0: Study set (discovery/validation)\n", " # Row 1: Sample type (biopsy/total RNA)\n", " # Row 2: Specimen IDs\n", " # Row 3: Tissue and normal status\n", " # Row 4: CKD status\n", " \n", " # Create a proper DataFrame for the clinical data\n", " # Sample characteristics as provided\n", " sample_char_dict = {\n", " 0: ['study set: discovery set', 'study set: validation set'], \n", " 1: ['sample type: Renal biopsy specimens', 'sample type: Normal kidney total RNA'], \n", " 2: ['specimen id: #01', 'specimen id: #02', 'specimen id: #03', 'specimen id: #04', \n", " 'specimen id: #05', 'specimen id: #06', 'specimen id: #07', 'specimen id: #08', \n", " 'specimen id: #09', 'specimen id: #10', 'specimen id: #11', 'specimen id: #12', \n", " 'specimen id: #13', 'specimen id: #14', 'specimen id: #15', 'specimen id: #16', \n", " 'specimen id: #17', 'specimen id: #18', 'specimen id: #19', 'specimen id: #20', \n", " 'specimen id: #21', 'specimen id: #22', 'specimen id: #23', 'specimen id: #24', \n", " 'specimen id: #26', 'specimen id: #27', 'specimen id: #28', 'specimen id: #29', \n", " 'specimen id: #30', 'specimen id: #31'], \n", " 3: ['tissue: kidney', 'disease status: normal kidney'], \n", " 4: ['disease status: chronic kidney disease (CKD)', float('nan')]\n", " }\n", " \n", " # From the data and background information, we can infer:\n", " # - Row 3 contains normal kidney status\n", " # - Row 4 contains CKD status\n", " # We need to determine which samples are normal and which are CKD\n", " \n", " # First, extract all sample IDs\n", " sample_ids = []\n", " for sample_info in sample_char_dict[2]:\n", " if 'specimen id:' in sample_info:\n", " sample_id = sample_info.split(':', 1)[1].strip()\n", " sample_ids.append(sample_id)\n", " \n", " # Create a clinical DataFrame with samples as columns\n", " clinical_data = pd.DataFrame(index=range(5), columns=sample_ids)\n", " \n", " # Based on the study design described in background info, we'll assign:\n", " # - Normal samples as those from \"normal kidney total RNA\" (row 1, index 1)\n", " # - CKD samples as those from \"Renal biopsy specimens\" (row 1, index 0)\n", " \n", " # Fill in the trait values for each sample\n", " for i, sample_id in enumerate(sample_ids):\n", " # If we have more sample IDs than values in row 1, assume remaining are from first category\n", " if i < len(sample_char_dict[1]):\n", " sample_type = sample_char_dict[1][min(i, len(sample_char_dict[1])-1)]\n", " else:\n", " sample_type = sample_char_dict[1][0]\n", " \n", " # Determine disease status based on sample type\n", " if \"Normal kidney total RNA\" in sample_type:\n", " clinical_data.at[3, sample_id] = \"disease status: normal kidney\"\n", " clinical_data.at[4, sample_id] = float('nan')\n", " else:\n", " clinical_data.at[3, sample_id] = \"tissue: kidney\"\n", " clinical_data.at[4, sample_id] = \"disease status: chronic kidney disease (CKD)\"\n", " \n", " # Fill in other rows for completeness\n", " for i in range(3):\n", " for j, sample_id in enumerate(sample_ids):\n", " if j < len(sample_char_dict[i]):\n", " clinical_data.at[i, sample_id] = sample_char_dict[i][min(j, len(sample_char_dict[i])-1)]\n", " else:\n", " clinical_data.at[i, sample_id] = sample_char_dict[i][0]\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 resulting dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data to a CSV file\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": "9ea75612", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "be86c517", "metadata": {}, "outputs": [], "source": [ "# Check if the dataset contains gene expression data based on previous assessment\n", "if not is_gene_available:\n", " print(\"This dataset does not contain gene expression data (only miRNA data).\")\n", " print(\"Skipping gene expression data extraction.\")\n", "else:\n", " # Get the matrix file directly rather than using geo_get_relevant_filepaths\n", " files = os.listdir(in_cohort_dir)\n", " if len(files) > 0:\n", " matrix_file = os.path.join(in_cohort_dir, files[0])\n", " print(f\"Matrix file found: {matrix_file}\")\n", " \n", " try:\n", " # Extract gene data\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # Print the first 20 gene/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", " else:\n", " print(\"No files found in the input directory.\")\n" ] }, { "cell_type": "markdown", "id": "b8added3", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "ae3554a0", "metadata": {}, "outputs": [], "source": [ "# Based on the gene identifiers shown (A_23_P format), these are Agilent microarray probe IDs,\n", "# not standard human gene symbols. These probe IDs need to be mapped to human gene symbols\n", "# for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "0ebbc07c", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "4a04fb9b", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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", "# Look more closely at columns that might contain gene information\n", "print(\"\\nExamining potential gene mapping columns:\")\n", "potential_gene_columns = ['gene_assignment', 'mrna_assignment', 'swissprot', 'unigene']\n", "for col in potential_gene_columns:\n", " if col in gene_annotation.columns:\n", " print(f\"\\nSample values from '{col}' column:\")\n", " print(gene_annotation[col].head(3).tolist())\n" ] }, { "cell_type": "markdown", "id": "4c80bf61", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "031b632e", "metadata": {}, "outputs": [], "source": [ "# 1. Determine which columns store probe identifiers and gene symbols\n", "# From examining the gene annotation, we can see:\n", "# - 'ID' column contains probe identifiers like 'A_23_P100001'\n", "# - 'GENE_SYMBOL' column contains the gene symbols like 'FAM174B'\n", "\n", "print(\"\\nMapping probe IDs to gene symbols:\")\n", "prob_col = 'ID' # Column for probe identifiers\n", "gene_col = 'GENE_SYMBOL' # Column for gene symbols\n", "\n", "# 2. Get gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "print(f\"First 5 rows of mapping data:\")\n", "print(preview_df(mapping_df, n=5))\n", "\n", "# 3. Apply gene mapping to convert probe measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(f\"First 10 gene symbols after mapping:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Save the gene expression data to CSV\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": "ad2d5a8d", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "e9ff536a", "metadata": {}, "outputs": [], "source": [ "# Load the clinical data from the file we saved in step 2\n", "clinical_data_file = out_clinical_data_file\n", "if os.path.exists(clinical_data_file):\n", " selected_clinical_df = pd.read_csv(clinical_data_file)\n", " print(f\"Loaded clinical data from {clinical_data_file}\")\n", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(selected_clinical_df.head())\n", "else:\n", " print(f\"Clinical data file {clinical_data_file} not found. Re-extracting 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", " print(\"Re-extracted clinical data preview:\")\n", " print(preview_df(selected_clinical_df))\n", "\n", "# 1. Normalize gene symbols in the index\n", "print(\"\\nNormalizing gene symbols...\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "print(\"First 10 gene identifiers after normalization:\")\n", "print(normalized_gene_data.index[:10].tolist())\n", "\n", "# Save the normalized gene data to CSV\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "# Since we read clinical data with a standard index (0, 1, 2...), need to transpose before linking\n", "if 'Liver_Cancer' in selected_clinical_df.columns:\n", " selected_clinical_df.set_index('Liver_Cancer', inplace=True)\n", " selected_clinical_df = selected_clinical_df.T\n", "else:\n", " # Transpose to get samples as rows and trait as column\n", " selected_clinical_df = selected_clinical_df.T\n", " selected_clinical_df.columns = [trait]\n", "\n", "linked_data = pd.concat([selected_clinical_df, normalized_gene_data.T], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", "print(linked_data.iloc[:5, :5])\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\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Determine if 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. Conduct final quality validation and save relevant information\n", "print(\"\\nConducting final quality validation...\")\n", "is_gene_available = len(normalized_gene_data) > 0\n", "is_trait_available = True # We've confirmed trait data is available in previous steps\n", "\n", "note = \"This dataset contains gene expression data from skin biopsies of patients with alopecia areata, comparing lesional and non-lesional samples. The dataset is actually about alopecia areata, not liver cancer.\"\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=is_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 6. Save the linked data if it's usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Linked data not saved as dataset is not usable for the current trait study.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }