{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "43e8e3eb", "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 = \"GSE148346\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Liver_Cancer/GSE148346\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_Cancer/GSE148346.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_Cancer/gene_data/GSE148346.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_Cancer/clinical_data/GSE148346.csv\"\n", "json_path = \"../../output/preprocess/Liver_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "aca27251", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "2441e1ee", "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": "3fed88e7", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "7455ed4f", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# From the background information, this is a study on alopecia areata (AA) with molecular response data\n", "# This indicates gene expression data is likely available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Looking at the sample characteristics dictionary\n", "\n", "# 2.1 For the trait (Liver Cancer)\n", "# Looking at the background information and sample characteristics, this dataset doesn't appear to be about liver cancer\n", "# It's a study on alopecia areata (AA)\n", "# Key 3 shows 'tissue disease state: LS', 'tissue disease state: NL' which relates to lesional (LS) and non-lesional (NL) skin\n", "trait_row = 3 # Using tissue disease state as our trait indicator\n", "\n", "# For age - Not available in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# For gender - Not available in the sample characteristics dictionary\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary (1 for lesional, 0 for non-lesional)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " value_str = str(value).strip()\n", " if \":\" in value_str:\n", " value_str = value_str.split(\":\", 1)[1].strip()\n", " \n", " if value_str.upper() == \"LS\":\n", " return 1 # Lesional skin\n", " elif value_str.upper() == \"NL\":\n", " return 0 # Non-lesional skin\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous (Not used in this dataset)\"\"\"\n", " return None # Placeholder since age data is not available\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (Not used in this dataset)\"\"\"\n", " return None # Placeholder since gender data is not available\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available\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", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # If trait data is available, extract clinical features\n", " clinical_df = geo_select_clinical_features(\n", " clinical_data, # Assuming clinical_data is available from previous step\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 dataframe\n", " preview = preview_df(clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " 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": "b0820472", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "d1276930", "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": "1bfa072a", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "1d4935c2", "metadata": {}, "outputs": [], "source": [ "# These identifiers (\"1007_s_at\", \"1053_at\", etc.) are Affymetrix probe IDs from a microarray platform,\n", "# not standard human gene symbols. They need to be mapped to official gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "efc29dbe", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "69b41cf8", "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": "aadb4c4f", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "62835c6d", "metadata": {}, "outputs": [], "source": [ "# Identify the columns for mapping\n", "# From the gene annotation preview, I can see that:\n", "# - 'ID' column contains the probe identifiers (e.g., '1007_s_at')\n", "# - 'Gene Symbol' column contains the gene symbols (e.g., 'DDR1 /// MIR4640')\n", "\n", "# 1. Get the mapping between probe IDs and gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "\n", "# Print mapping dataframe info\n", "print(\"\\nGene mapping dataframe info:\")\n", "print(f\"Shape: {mapping_df.shape}\")\n", "print(mapping_df.head())\n", "\n", "# 2. Apply the mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# 3. Normalize gene symbols (handle synonyms and merge duplicate symbols)\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "# Print gene expression data info\n", "print(\"\\nGene expression data info after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(f\"First 5 gene symbols: {gene_data.index[:5].tolist()}\")\n", "print(f\"First 5 sample IDs: {gene_data.columns[:5].tolist()}\")\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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "3c223b69", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "acf55804", "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 }