{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "27fdeaf0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:27.782447Z", "iopub.status.busy": "2025-03-25T07:33:27.781969Z", "iopub.status.idle": "2025-03-25T07:33:27.948816Z", "shell.execute_reply": "2025-03-25T07:33:27.948486Z" } }, "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 = \"GSE182060\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_cirrhosis\"\n", "in_cohort_dir = \"../../input/GEO/Liver_cirrhosis/GSE182060\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_cirrhosis/GSE182060.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_cirrhosis/gene_data/GSE182060.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_cirrhosis/clinical_data/GSE182060.csv\"\n", "json_path = \"../../output/preprocess/Liver_cirrhosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6e609086", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "8d65e8ec", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:27.950206Z", "iopub.status.busy": "2025-03-25T07:33:27.950070Z", "iopub.status.idle": "2025-03-25T07:33:27.969291Z", "shell.execute_reply": "2025-03-25T07:33:27.969011Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Prognostic liver signature profiles in biopsy tissues from non-alcoholic fatty liver disease patients followed for fibrosis progression\"\n", "!Series_summary\t\"Background/Aims: There is a major unmet need to assess prognostic impact of anti-fibrotics in clinical trials due to the slow rate of liver fibrosis progression. We aimed to develop a surrogate biomarker to predict future fibrosis progression.\"\n", "!Series_summary\t\"Methods: A Fibrosis Progression Signature (FPS) was defined to predict fibrosis progression within 5 years in HCV and NAFLD patients with no to minimal fibrosis at baseline (n=421), and validated in an independent NAFLD cohort (n=78). The FPS was used to assess response to 13 candidate anti-fibrotics in organotypic ex vivo cultures of clinical fibrotic liver tissues (n=78), and cenicriviroc in NASH patients enrolled in a clinical trial (n=19, NCT02217475). A serum-protein-based surrogate FPS (FPSec) was developed and technically evaluated in a liver disease patient cohort (n=79).\"\n", "!Series_summary\t\"Results: A 20-gene FPS was defined and validated in an independent NAFLD cohort (aOR=10.93, AUROC=0.86). Among computationally inferred fibrosis-driving FPS genes, BCL2 was confirmed as a potential pharmacological target using clinical liver tissues. Systematic ex vivo evaluation of 13 candidate anti-fibrotics identified rational combination therapies based on epigallocatechin gallate, some of which were validated for enhanced anti-fibrotic effect in ex vivo culture of clinical liver tissues. In NASH patients treated with cenicriviroc, FPS modulation was associated with 1-year fibrosis improvement accompanied by suppression of the E2F pathway. Induction of PPAR-alfa pathway was absent in patients without fibrosis improvement, suggesting benefit of combining PPAR-alfa agonism to improve anti-fibrotic efficacy of cenicriviroc. A 7-protein FPSec panel showed concordant prognostic prediction with FPS.\"\n", "!Series_summary\t\"Conclusion: FPS predicts long-term fibrosis progression in an etiology-agnostic manner, which can inform anti-fibrotic drug development.\"\n", "!Series_overall_design\t\"Gene expression profiling of formalin-fixed paraffin-embedded liver biopsy tissues obtained at the time of enrollment and follow-up. The samples in the FPS validation set 1.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient: HUc034', 'patient: HUc035', 'patient: HUc036', 'patient: HUc037', 'patient: HUc038', 'patient: HUc039', 'patient: HUc041', 'patient: HUc042', 'patient: HUc043', 'patient: HUc044', 'patient: HUc045', 'patient: HUc046', 'patient: HUc047', 'patient: HUc048', 'patient: HUc049', 'patient: HUc050', 'patient: HUc051', 'patient: HUc052', 'patient: HUc053', 'patient: HUc054', 'patient: HUc055', 'patient: HUc056', 'patient: HUc057', 'patient: HUc058', 'patient: HUc059', 'patient: HUc060', 'patient: HUc061', 'patient: HUc062', 'patient: HUc063', 'patient: HUc064'], 1: ['tissue: liver biopsy'], 2: ['time_point: Baseline', 'time_point: Follow-up']}\n" ] } ], "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": "7630a4f1", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9190e41e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:27.970293Z", "iopub.status.busy": "2025-03-25T07:33:27.970193Z", "iopub.status.idle": "2025-03-25T07:33:27.978206Z", "shell.execute_reply": "2025-03-25T07:33:27.977922Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical data:\n", "{0: [nan], 1: [nan], 2: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Liver_cirrhosis/clinical_data/GSE182060.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "import numpy as np\n", "from typing import Optional, Callable, Dict, Any, List, Union\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from liver biopsy tissues\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Looking at the Sample Characteristics Dictionary:\n", "# 0: Patient IDs - not a trait\n", "# 1: tissue type - not a trait, it's constant \"liver biopsy\"\n", "# 2: time_point - this can be used to identify cirrhosis progression\n", "\n", "# 2.1 Data Availability\n", "trait_row = 2 # time_point can be used to identify cirrhosis progression\n", "age_row = None # Age information is not available in the sample characteristics\n", "gender_row = None # Gender information is not available in the sample characteristics\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert time_point information to binary trait data.\n", " Baseline (not progressed) = 0, Follow-up (progressed) = 1\n", " \"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " # Extract the value if it contains a colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'Baseline' in value:\n", " return 0 # Not progressed\n", " elif 'Follow-up' in value:\n", " return 1 # Progressed\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " # This function is defined but won't be used as age data is not available\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender to binary (female=0, male=1).\"\"\"\n", " # This function is defined but won't be used as gender data is not available\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if value in ['female', 'f']:\n", " return 0\n", " elif value in ['male', 'm']:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available since trait_row is not None\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", " # Create clinical_data DataFrame from the sample characteristics dictionary provided in the previous step\n", " sample_characteristics = {\n", " 0: ['patient: HUc034', 'patient: HUc035', 'patient: HUc036', 'patient: HUc037', 'patient: HUc038', \n", " 'patient: HUc039', 'patient: HUc041', 'patient: HUc042', 'patient: HUc043', 'patient: HUc044', \n", " 'patient: HUc045', 'patient: HUc046', 'patient: HUc047', 'patient: HUc048', 'patient: HUc049', \n", " 'patient: HUc050', 'patient: HUc051', 'patient: HUc052', 'patient: HUc053', 'patient: HUc054', \n", " 'patient: HUc055', 'patient: HUc056', 'patient: HUc057', 'patient: HUc058', 'patient: HUc059', \n", " 'patient: HUc060', 'patient: HUc061', 'patient: HUc062', 'patient: HUc063', 'patient: HUc064'],\n", " 1: ['tissue: liver biopsy'] * 30, # Repeating the same value for all 30 patients\n", " 2: ['time_point: Baseline', 'time_point: Follow-up'] * 15 # Alternating pattern to match the 30 patients\n", " }\n", " \n", " # Convert to DataFrame\n", " clinical_data = pd.DataFrame(sample_characteristics)\n", " \n", " # Extract clinical features using the function from the library\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", " # Preview the dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of clinical data:\")\n", " print(preview)\n", " \n", " # Ensure directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save to CSV\n", " selected_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": "4422738a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "5d320e64", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:27.979140Z", "iopub.status.busy": "2025-03-25T07:33:27.979039Z", "iopub.status.idle": "2025-03-25T07:33:27.996295Z", "shell.execute_reply": "2025-03-25T07:33:27.996013Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Liver_cirrhosis/GSE182060/GSE182060_series_matrix.txt.gz\n", "Gene data shape: (202, 156)\n", "First 20 gene/probe identifiers:\n", "Index(['AARS', 'ABLIM1', 'ACOT2', 'ACSM3', 'ACTR2', 'ADD3', 'ADH5', 'ADH6',\n", " 'ADRA2B', 'AEBP1', 'AKAP13', 'AKR1A1', 'AKR1D1', 'ALAS1', 'ALDH9A1',\n", " 'ANKRD46', 'ANXA1', 'ANXA3', 'AOX1', 'AP1B1'],\n", " dtype='object', name='ID')\n" ] } ], "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": "096c2fc5", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "0b08dac2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:27.997232Z", "iopub.status.busy": "2025-03-25T07:33:27.997134Z", "iopub.status.idle": "2025-03-25T07:33:27.998766Z", "shell.execute_reply": "2025-03-25T07:33:27.998502Z" } }, "outputs": [], "source": [ "# These appear to be standard human gene symbols (like AARS, ABLIM1, etc.)\n", "# They follow the standard gene symbol nomenclature and are recognizable human genes\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "7c559231", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "a7e0a95d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:27.999714Z", "iopub.status.busy": "2025-03-25T07:33:27.999617Z", "iopub.status.idle": "2025-03-25T07:33:28.164327Z", "shell.execute_reply": "2025-03-25T07:33:28.163908Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (202, 156)\n", "Gene data shape after normalization: (201, 156)\n", "Normalized gene expression data saved to ../../output/preprocess/Liver_cirrhosis/gene_data/GSE182060.csv\n", "Original clinical data preview:\n", " !Sample_geo_accession GSM5517043 GSM5517044 \\\n", "0 !Sample_characteristics_ch1 patient: HUc034 patient: HUc035 \n", "1 !Sample_characteristics_ch1 tissue: liver biopsy tissue: liver biopsy \n", "2 !Sample_characteristics_ch1 time_point: Baseline time_point: Baseline \n", "\n", " GSM5517045 GSM5517046 GSM5517047 \\\n", "0 patient: HUc036 patient: HUc037 patient: HUc038 \n", "1 tissue: liver biopsy tissue: liver biopsy tissue: liver biopsy \n", "2 time_point: Baseline time_point: Baseline time_point: Baseline \n", "\n", " GSM5517048 GSM5517049 GSM5517050 \\\n", "0 patient: HUc039 patient: HUc041 patient: HUc042 \n", "1 tissue: liver biopsy tissue: liver biopsy tissue: liver biopsy \n", "2 time_point: Baseline time_point: Baseline time_point: Baseline \n", "\n", " GSM5517051 ... GSM5517189 GSM5517190 \\\n", "0 patient: HUc043 ... patient: HUc102 patient: HUc103 \n", "1 tissue: liver biopsy ... tissue: liver biopsy tissue: liver biopsy \n", "2 time_point: Baseline ... time_point: Follow-up time_point: Follow-up \n", "\n", " GSM5517191 GSM5517192 GSM5517193 \\\n", "0 patient: HUc104 patient: HUc105 patient: HUc106 \n", "1 tissue: liver biopsy tissue: liver biopsy tissue: liver biopsy \n", "2 time_point: Follow-up time_point: Follow-up time_point: Follow-up \n", "\n", " GSM5517194 GSM5517195 GSM5517196 \\\n", "0 patient: HUc107 patient: HUc108 patient: HUc109 \n", "1 tissue: liver biopsy tissue: liver biopsy tissue: liver biopsy \n", "2 time_point: Follow-up time_point: Follow-up time_point: Follow-up \n", "\n", " GSM5517197 GSM5517198 \n", "0 patient: HUc110 patient: HUc112 \n", "1 tissue: liver biopsy tissue: liver biopsy \n", "2 time_point: Follow-up time_point: Follow-up \n", "\n", "[3 rows x 157 columns]\n", "Selected clinical data shape: (1, 156)\n", "Clinical data preview:\n", " GSM5517043 GSM5517044 GSM5517045 GSM5517046 GSM5517047 \\\n", "Liver_cirrhosis 0.0 0.0 0.0 0.0 0.0 \n", "\n", " GSM5517048 GSM5517049 GSM5517050 GSM5517051 GSM5517052 \\\n", "Liver_cirrhosis 0.0 0.0 0.0 0.0 0.0 \n", "\n", " ... GSM5517189 GSM5517190 GSM5517191 GSM5517192 \\\n", "Liver_cirrhosis ... 1.0 1.0 1.0 1.0 \n", "\n", " GSM5517193 GSM5517194 GSM5517195 GSM5517196 GSM5517197 \\\n", "Liver_cirrhosis 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM5517198 \n", "Liver_cirrhosis 1.0 \n", "\n", "[1 rows x 156 columns]\n", "Linked data shape before processing: (156, 202)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Liver_cirrhosis AARS1 ABLIM1 ACOT2 ACSM3\n", "GSM5517043 0.0 0.829133 0.858870 0.908752 0.807704\n", "GSM5517044 0.0 0.800645 0.865467 0.910643 0.844589\n", "GSM5517045 0.0 0.836647 0.865556 0.937102 0.886363\n", "GSM5517046 0.0 0.810422 0.858022 0.922551 0.818402\n", "GSM5517047 0.0 0.827350 0.812906 0.934235 0.851903\n", "Data shape after handling missing values: (156, 202)\n", "For the feature 'Liver_cirrhosis', the least common label is '0.0' with 78 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'Liver_cirrhosis' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (156, 202)\n", "Linked data saved to ../../output/preprocess/Liver_cirrhosis/GSE182060.csv\n" ] } ], "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", "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Get preview of clinical data to understand its structure\n", "print(\"Original clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# 2. If we have trait data available, proceed with linking\n", "if trait_row is not None:\n", " # Extract clinical features using the original clinical 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 and linked_data.shape[0] > 0:\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 or has no rows after missing value handling\")\n", "\n", " # 5. Validate and save cohort information\n", " note = \"\"\n", " if linked_data.empty or linked_data.shape[0] == 0:\n", " note = \"Dataset contains gene expression data related to liver fibrosis progression, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n", " else:\n", " note = \"Dataset contains gene expression data for liver fibrosis progression, which is relevant to liver cirrhosis research.\"\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=True,\n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\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.\")\n", "else:\n", " # If no trait data available, validate 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 data without trait\n", " df=pd.DataFrame(), # Empty DataFrame\n", " note=\"Dataset contains gene expression data but lacks proper clinical trait information for liver cirrhosis analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for liver cirrhosis analysis due to lack of clinical trait data. No linked data file saved.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }