{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "3cbaeb4c", "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 = \"Liver_Cancer\"\n", "cohort = \"GSE212047\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Liver_Cancer/GSE212047\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_Cancer/GSE212047.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_Cancer/gene_data/GSE212047.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_Cancer/clinical_data/GSE212047.csv\"\n", "json_path = \"../../output/preprocess/Liver_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a780c3b1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "3b51c9db", "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": "d2f7852f", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "39a9e818", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# Let's analyze the dataset\n", "# The sample characteristics dictionary doesn't represent a proper dataframe\n", "# We need to use the original data correctly and avoid manual construction\n", "sample_characteristics = {\n", " 0: ['strain: Lhx2 floxed; C57BL/6J background', 'strain: Mx1Cre+; Lhx2 floxed; C57BL/6J background'],\n", " 1: ['treatment: 2 weeks after poly:IC induce Mx1Cre activation'],\n", " 2: ['cell type: FACS-sorted VitA+ Hepatic Stellate Cells']\n", "}\n", "\n", "# 1. Gene Expression Data Availability\n", "# The background info mentions bulk RNAseq and microarray data, which would contain 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 trait (Liver Cancer):\n", "# Looking at the data, there's no explicit mention of cancer/non-cancer status in sample characteristics.\n", "# This appears to be mouse liver tissue samples with genetic modifications, not human cancer samples.\n", "trait_row = None # Not available in the sample characteristics\n", "\n", "# For age:\n", "# No age data is provided in the sample characteristics\n", "age_row = None\n", "\n", "# For gender:\n", "# No gender data is provided in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "# Define conversion functions even though we won't use them\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " \n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'cancer' in value or 'tumor' in value or 'hcc' in value:\n", " return 1\n", " elif 'normal' in value or 'control' in value or 'non-tumor' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if value is None:\n", " return None\n", " \n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \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", " \n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Since trait_row is None, is_trait_available is False\n", "is_trait_available = trait_row is not None\n", "\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 None, we skip this step\n" ] }, { "cell_type": "markdown", "id": "c7b3e360", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "dde0280f", "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": "68282f3f", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "4b6c2af4", "metadata": {}, "outputs": [], "source": [ "# These don't appear to be standard human gene symbols, which would typically be like BRCA1, TP53, etc.\n", "# They look like probe identifiers or some other form of ID on a microarray platform (GPL6246).\n", "# These numeric IDs need to be mapped to actual gene symbols for meaningful analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "288894b8", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "51edcc40", "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": "27ce340b", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "1026bf16", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the columns for mapping\n", "# Looking at the gene annotation preview, we need:\n", "# - 'ID' column in gene_annotation for the probe identifiers\n", "# - 'gene_assignment' column for the gene symbols\n", "\n", "# Print information to help verify the mapping\n", "print(\"\\nChecking gene identifiers in both datasets:\")\n", "print(f\"Sample IDs in gene_data: {gene_data.index[:5].tolist()}\")\n", "print(f\"Sample IDs in gene_annotation: {gene_annotation['ID'][:5].tolist()}\")\n", "\n", "# 2. Get gene mapping dataframe\n", "# First, let's examine the format of gene_assignment more closely\n", "print(\"\\nExamining 'gene_assignment' format for mapping strategy:\")\n", "print(gene_annotation['gene_assignment'].iloc[0])\n", "\n", "# Create the gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'gene_assignment')\n", "print(f\"\\nGene mapping dataframe created with shape: {mapping_df.shape}\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level to gene expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"\\nMapped gene expression data shape: {gene_data.shape}\")\n", "\n", "# Save the gene expression data\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\"Mapped gene data saved to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "d39683f7", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "a270e338", "metadata": {}, "outputs": [], "source": [ "# 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", "# Based on Step 2, we determined trait_row was None, meaning no trait data is available\n", "print(\"\\nNo human trait data is available in this dataset.\")\n", "is_gene_available = len(normalized_gene_data) > 0\n", "is_trait_available = False # We know this from Step 2\n", "is_biased = None # Cannot determine bias without trait data\n", "\n", "# Create empty DataFrame for consistency in validation\n", "linked_data_clean = pd.DataFrame()\n", "\n", "# 5. Conduct final quality validation and save metadata\n", "print(\"\\nConducting final quality validation...\")\n", "note = \"This dataset contains mouse gene expression data without human trait information. The data appears to be from mouse hepatic stellate cells with genetic modifications (Lhx2 floxed), not suitable for human liver cancer association studies.\"\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_clean,\n", " note=note\n", ")\n", "\n", "print(\"Dataset deemed not usable for human trait associative studies due to lack of trait data.\")\n" ] }, { "cell_type": "markdown", "id": "06b6d09a", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "c644d42c", "metadata": {}, "outputs": [], "source": [ "# 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", "# Based on Step 2, we determined that trait data is not available in this dataset\n", "print(\"\\nNo clinical trait data is available in this dataset.\")\n", "\n", "# Create empty DataFrame for validation\n", "# Since we determined in Step 2 that trait data is not available\n", "empty_clinical_df = pd.DataFrame()\n", "linked_data = pd.DataFrame()\n", "\n", "# Set up variables for validation\n", "is_gene_available = len(normalized_gene_data) > 0\n", "is_trait_available = False # We know this from Step 2\n", "is_biased = False # Setting a default value for validation\n", "\n", "# 5. Conduct final quality validation and save metadata\n", "print(\"\\nConducting final quality validation...\")\n", "note = \"This dataset contains mouse gene expression data without human trait information. The data appears to be from mouse hepatic stellate cells with genetic modifications (Lhx2 floxed), not suitable for human liver cancer association studies.\"\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=empty_clinical_df,\n", " note=note\n", ")\n", "\n", "print(\"Dataset deemed not usable for human trait associative studies due to lack of trait data.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }