{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "6b78dc44", "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_cirrhosis\"\n", "cohort = \"GSE185529\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_cirrhosis\"\n", "in_cohort_dir = \"../../input/GEO/Liver_cirrhosis/GSE185529\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_cirrhosis/GSE185529.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_cirrhosis/gene_data/GSE185529.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_cirrhosis/clinical_data/GSE185529.csv\"\n", "json_path = \"../../output/preprocess/Liver_cirrhosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "656fdf80", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "c39a895e", "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": "66786c37", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "b3ec5fc3", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this appears to focus on genes (BNC2) regulated in myofibroblasts\n", "# and liver fibrosis, but we need to be cautious as it's a SuperSeries composed of SubSeries.\n", "# Without seeing the actual gene data, we'll assume it likely contains gene expression data.\n", "is_gene_available = True # Set to True assuming gene expression data is available\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary, we only see 'treatment' information\n", "# There is no explicit trait (liver cirrhosis), age, or gender information\n", "trait_row = None # No explicit liver cirrhosis trait information\n", "age_row = None # No age information\n", "gender_row = None # No gender information\n", "\n", "# 2.2 Data Type Conversion Functions\n", "# Since we don't have trait, age, or gender data, these functions are placeholders\n", "def convert_trait(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value_str = str(value)\n", " if ':' in value_str:\n", " value_str = value_str.split(':', 1)[1].strip()\n", " \n", " # For liver cirrhosis, typically would convert to binary (0: no cirrhosis, 1: cirrhosis)\n", " # But since we don't have the data, this is just a placeholder\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value_str = str(value)\n", " if ':' in value_str:\n", " value_str = value_str.split(':', 1)[1].strip()\n", " \n", " # Would convert to continuous numeric value\n", " # But since we don't have the data, this is just a placeholder\n", " return None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value_str = str(value)\n", " if ':' in value_str:\n", " value_str = value_str.split(':', 1)[1].strip().lower()\n", " \n", " # Would convert to binary (0: female, 1: male)\n", " # But since we don't have the data, this is just a placeholder\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability based on whether trait_row is None\n", "is_trait_available = trait_row is not None\n", "\n", "# Save the initial filtering results\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", "# Skip this step since trait_row is None (clinical data not available for our needed traits)\n" ] }, { "cell_type": "markdown", "id": "1265d380", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "10bea7ea", "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": "c24eac0c", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "f5dfe2cb", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers in the data\n", "# These identifiers (like '2824546_st') are not standard human gene symbols\n", "# They appear to be probe IDs from a microarray platform (GPL17586)\n", "# These would need to be mapped to standard gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "44aa7d8a", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "b90179e0", "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. 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", "# Check for gene information in the SPOT_ID.1 column which appears to contain gene names\n", "print(\"\\nAnalyzing SPOT_ID.1 column for gene symbols:\")\n", "if 'SPOT_ID.1' in gene_annotation.columns:\n", " # Extract a few sample values\n", " sample_values = gene_annotation['SPOT_ID.1'].head(3).tolist()\n", " for i, value in enumerate(sample_values):\n", " print(f\"Sample {i+1} excerpt: {value[:200]}...\") # Print first 200 chars\n", " # Test the extract_human_gene_symbols function on these values\n", " symbols = extract_human_gene_symbols(value)\n", " print(f\" Extracted gene symbols: {symbols}\")\n", "\n", "# Try to find the probe IDs in the gene annotation\n", "gene_data_id_prefix = gene_data.index[0].split('_')[0] # Get prefix of first gene ID\n", "print(f\"\\nGene data ID prefix: {gene_data_id_prefix}\")\n", "\n", "# Look for columns that might match the gene data IDs\n", "for col in gene_annotation.columns:\n", " if gene_annotation[col].astype(str).str.contains(gene_data_id_prefix).any():\n", " print(f\"Column '{col}' contains values matching gene data ID pattern\")\n", "\n", "# Check if there's any column that might contain transcript or gene IDs\n", "print(\"\\nChecking for columns containing transcript or gene related terms:\")\n", "for col in gene_annotation.columns:\n", " if any(term in col.upper() for term in ['GENE', 'TRANSCRIPT', 'SYMBOL', 'NAME', 'DESCRIPTION']):\n", " print(f\"Column '{col}' may contain gene-related information\")\n", " # Show sample values\n", " print(f\"Sample values: {gene_annotation[col].head(3).tolist()}\")\n" ] }, { "cell_type": "markdown", "id": "4ed5cb45", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "0081992f", "metadata": {}, "outputs": [], "source": [ "# Extract the probe_id and gene_symbols from gene_annotation\n", "# Looking at the gene_data IDs (2824546_st) and the gene_annotation data\n", "# Need to map between probe IDs and gene symbols\n", "\n", "# Create a mapping between the probe IDs in gene_data and gene symbols\n", "# The ID column in gene_annotation needs to be linked to the probe IDs in gene_data\n", "# We need to explore how the IDs match up\n", "\n", "# Extract the ID suffix pattern from gene_data\n", "id_pattern = gene_data.index[0].split('_')[1] # Should be \"st\"\n", "print(f\"ID suffix pattern in gene_data: {id_pattern}\")\n", "\n", "# Check how the IDs in gene_annotation can be matched to gene_data\n", "sample_gene_data_ids = gene_data.index[:5].tolist()\n", "print(f\"Sample gene data IDs: {sample_gene_data_ids}\")\n", "\n", "# Looking at \"gene_assignment\" column which contains gene symbols\n", "# First check if gene_assignment actually contains mappable data (not all \"---\")\n", "gene_mappings_available = gene_annotation['gene_assignment'].apply(lambda x: x != '---').sum()\n", "print(f\"Number of rows with gene mappings: {gene_mappings_available} out of {len(gene_annotation)}\")\n", "\n", "# 1. Create the gene mapping dataframe\n", "# We'll map from the ID in gene_annotation to the gene symbols in gene_assignment\n", "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'gene_assignment')\n", "print(f\"Gene mapping shape: {mapping_df.shape}\")\n", "print(\"First few mappings:\")\n", "print(mapping_df.head())\n", "\n", "# 2. Apply the gene mapping to convert probe-level measurements to gene expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Mapped gene data shape: {gene_data.shape}\")\n", "print(\"First few genes:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene 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 data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "d1dd3de8", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "f92245e2", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# Use normalize_gene_symbols_in_index to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data to file\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 expression data saved to {out_gene_data_file}\")\n", "\n", "# Check if trait_row is None (indicating no clinical data is available)\n", "if trait_row is None:\n", " print(\"No clinical data available for this dataset, skipping clinical data processing.\")\n", " \n", " # Validate and save cohort information with trait_available=False\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=False,\n", " is_biased=True, # Set to True since we can't use this data without clinical features\n", " df=pd.DataFrame(), # Empty DataFrame since we have no linked data\n", " note=\"Dataset contains gene expression data from cell lines with HCV infection, which is not appropriate for liver cirrhosis trait analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for liver cirrhosis analysis due to lack of clinical data. No linked data file saved.\")\n", "else:\n", " # If clinical data is available, proceed with the linking and processing\n", " # 2. Link the clinical and genetic data\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", " print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(selected_clinical_df.head())\n", "\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before processing: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, 5 columns):\")\n", " print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n", "\n", " # 3. Handle missing values\n", " try:\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " linked_data = pd.DataFrame() # Create empty dataframe if error occurs\n", "\n", " # 4. Check for bias in features\n", " if not linked_data.empty:\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", " else:\n", " is_biased = True\n", " print(\"Cannot check for bias as dataframe is empty after missing value handling\")\n", "\n", " # 5. 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=True,\n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data for liver fibrosis progression, which is relevant to liver cirrhosis research.\"\n", " )\n", "\n", " # 6. Save the linked data if 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(\"Dataset is not usable for analysis. No linked data file saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }