{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "cabbce92", "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 = \"GSE178201\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Liver_Cancer/GSE178201\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_Cancer/GSE178201.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_Cancer/gene_data/GSE178201.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_Cancer/clinical_data/GSE178201.csv\"\n", "json_path = \"../../output/preprocess/Liver_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "4d06ec63", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "ec650ff6", "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": "aba21581", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "b53bd938", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Dict, Any, Callable, Optional\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, the dataset uses the L1000 platform\n", "# which measures the expression of ~1,000 landmark genes, so 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 trait (Liver_Cancer):\n", "# Looking at the tissues in the dataset, we see HEPG2 which is a hepatocellular carcinoma cell line\n", "# However, this dataset doesn't have a cancer vs non-cancer comparison - all samples are cancer cell lines\n", "# There's no row indicating cancer status as a variable being studied\n", "trait_row = None # No trait information for liver cancer comparison\n", "\n", "# For age:\n", "# No age information in the sample characteristics\n", "age_row = None\n", "\n", "# For gender:\n", "# No gender information in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary format.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # We would convert actual values here, but since trait_row is None, this function won't be used\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous format.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # We would convert actual values here, but since age_row is None, this function won't be used\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary format.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # We would convert actual values here, but since gender_row is None, this function won't be used\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait availability based on whether trait_row is None\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering on dataset usability\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'll skip the clinical feature extraction step\n" ] }, { "cell_type": "markdown", "id": "de6ab309", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "64be5885", "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": "c116ec5a", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "9ac7bd06", "metadata": {}, "outputs": [], "source": [ "# Based on the gene expression data identifiers provided (16, 23, 25, etc.),\n", "# these appear to be numeric IDs rather than standard human gene symbols.\n", "# Standard human gene symbols would be text-based identifiers like BRCA1, TP53, etc.\n", "# Therefore, these identifiers will require mapping to gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "46eb0f40", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "10835ae3", "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": "fa3bc63e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "2657f4e2", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the appropriate columns for mapping\n", "# Based on the gene annotation preview, 'ID' contains numeric identifiers similar to those\n", "# in the gene expression data, and 'pr_gene_symbol' contains the gene symbols\n", "\n", "# 2. Create gene mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='pr_gene_symbol')\n", "print(f\"\\nGene mapping preview (first 5 rows):\")\n", "print(preview_df(gene_mapping, n=5))\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"\\nGene data after mapping (now indexed by gene symbols):\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First 10 gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Optional: Normalize gene symbols to handle synonyms\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"\\nGene data after normalization:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First 10 normalized gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n" ] }, { "cell_type": "markdown", "id": "0d715dbe", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "a5e0707d", "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 trait data is available in this dataset for liver cancer comparison.\")\n", "\n", "# Use the clinical data that was loaded earlier instead of an empty DataFrame\n", "# Since the dataset has clinical data (cell lines and treatments), but no trait data for our purpose\n", "linked_data = clinical_data.copy()\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 = True # Since all samples are cancer cell lines, there's no control vs. cancer comparison\n", "\n", "# 5. Conduct final quality validation and save metadata\n", "print(\"\\nConducting final quality validation...\")\n", "note = \"This dataset contains gene expression data from human cell lines (HepG2 hepatocellular carcinoma and MCF10A breast cells) treated with different chemicals. However, it doesn't include a control vs. cancer comparison needed for 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,\n", " note=note\n", ")\n", "\n", "print(\"Dataset deemed not usable for liver cancer associative studies due to lack of appropriate trait data.\")\n", "\n", "# Save clinical data even though it doesn't contain our target trait\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_data.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# No need to save linked_data since the dataset is not usable for our trait analysis\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 }