{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "7a0d51cb", "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 = \"GSE69438\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Chronic_kidney_disease\"\n", "in_cohort_dir = \"../../input/GEO/Chronic_kidney_disease/GSE69438\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Chronic_kidney_disease/GSE69438.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Chronic_kidney_disease/gene_data/GSE69438.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE69438.csv\"\n", "json_path = \"../../output/preprocess/Chronic_kidney_disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "01d0ca9e", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "0b3449ac", "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": "fc501a27", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "d615115d", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "from typing import Optional, Dict, Any, Callable\n", "import json\n", "\n", "# Analyzing gene expression data availability\n", "# The background information mentions kidney tissue transcriptome data\n", "# This suggests gene expression data is likely available\n", "is_gene_available = True\n", "\n", "# Variable availability and data type conversion\n", "# From the sample characteristics dictionary, there's only information about the tissue source\n", "# There's no direct information about the trait (CKD), age, or gender\n", "\n", "# For trait: Based on the background information, this dataset is about Chronic Kidney Disease,\n", "# but the sample characteristics don't explicitly list which samples have CKD vs controls\n", "# Since the Series_overall_design mentions \"Chronic Kidney Disease\" and various nephropathies,\n", "# we can infer this is a study of CKD and its subtypes, but cannot determine trait status for individual samples\n", "trait_row = None\n", "\n", "# For age: No information available\n", "age_row = None\n", "\n", "# For gender: No information available\n", "gender_row = None\n", "\n", "# Since we can't extract trait information, we don't need conversion functions\n", "# but we'll define them as required\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " value = str(value).lower()\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Since we don't have actual trait data, this function is a placeholder\n", " return None\n", "\n", "def convert_age(value):\n", " if value is None:\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " value = str(value).lower()\n", " if \"female\" in value or \"f\" == value:\n", " return 0\n", " elif \"male\" in value or \"m\" == value:\n", " return 1\n", " return None\n", "\n", "# Save metadata using the validate_and_save_cohort_info function\n", "# Since trait_row is None, is_trait_available is False\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", "# Since trait_row is None, we skip the clinical feature extraction step\n" ] }, { "cell_type": "markdown", "id": "991b1171", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "3566c261", "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": "9fadcb5b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "f1990134", "metadata": {}, "outputs": [], "source": [ "# Analyzing the gene identifiers shown in the output\n", "# These appear to be Entrez Gene IDs (numeric identifiers), not gene symbols\n", "# For example, '1' is the Entrez ID for A1BG gene, '10' is for NAT2, etc.\n", "# These need to be mapped to human gene symbols for better interpretability\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "3f9ac76c", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "4bad7b3e", "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": "dae58cc8", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "3b1f1790", "metadata": {}, "outputs": [], "source": [ "# Determine which columns to use for mapping\n", "# From the gene annotation preview, we can see:\n", "# - 'ID' column contains the numeric identifiers (same as in gene expression data)\n", "# - 'ORF' column contains the gene symbols we want to map to\n", "\n", "# 1. Create the mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ORF')\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"First few rows of mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# 2. Apply the gene mapping to convert probe-level 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(\"First few gene symbols after mapping:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# 3. Save the gene expression data to a CSV file for future use\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": "0fe893c0", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "b2401fb0", "metadata": {}, "outputs": [], "source": [ "# Since we already determined this dataset doesn't have trait information (trait_row is None),\n", "# we need to skip the clinical data extraction and data linking steps.\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", "# For the final validation, we set is_trait_available to False since trait_row is None\n", "is_gene_available = len(normalized_gene_data) > 0\n", "is_trait_available = False # Confirmed in step 2\n", "\n", "# Create a dummy dataframe with required structure for validation\n", "dummy_df = pd.DataFrame({trait: [None]})\n", "\n", "# Set is_biased to True since the dataset is unusable due to missing trait information\n", "is_biased = True\n", "\n", "# Create a note about the dataset\n", "note = \"This dataset contains gene expression data for Chronic Kidney Disease, but lacks trait information distinguishing between cases and controls. The dataset cannot be used for the current trait study without clinical annotations.\"\n", "\n", "# 5. Conduct final quality validation and save relevant information\n", "print(\"\\nConducting final quality validation...\")\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=dummy_df,\n", " note=note\n", ")\n", "\n", "print(f\"Dataset usability: {is_usable}\")\n", "print(\"No linked data saved as dataset is not usable for the current trait study due to missing trait information.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }