{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "30aeea8a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:25.074910Z", "iopub.status.busy": "2025-03-25T07:33:25.074728Z", "iopub.status.idle": "2025-03-25T07:33:25.238507Z", "shell.execute_reply": "2025-03-25T07:33:25.238186Z" } }, "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 = \"GSE150734\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_cirrhosis\"\n", "in_cohort_dir = \"../../input/GEO/Liver_cirrhosis/GSE150734\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_cirrhosis/GSE150734.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_cirrhosis/gene_data/GSE150734.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_cirrhosis/clinical_data/GSE150734.csv\"\n", "json_path = \"../../output/preprocess/Liver_cirrhosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "cc583344", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "f274e1dc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:25.239928Z", "iopub.status.busy": "2025-03-25T07:33:25.239797Z", "iopub.status.idle": "2025-03-25T07:33:25.265622Z", "shell.execute_reply": "2025-03-25T07:33:25.265318Z" } }, "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 (NAFLD) patients in the U.S.\"\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. 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). 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 PPARalpha pathway was absent in patients without fibrosis improvement, suggesting benefit of combining PPARalpha agonism to improve anti-fibrotic efficacy of cenicriviroc. A 7-protein FPSec panel showed concordant prognostic prediction with FPS. 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. The samples for the FPS derivation set 4.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['fibrosis stage: 0', 'fibrosis stage: 1'], 1: ['pls risk prediction: High', 'pls risk prediction: Intermediate', 'pls risk prediction: Low']}\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": "0c2dadee", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "58b113e2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:25.266691Z", "iopub.status.busy": "2025-03-25T07:33:25.266592Z", "iopub.status.idle": "2025-03-25T07:33:25.273577Z", "shell.execute_reply": "2025-03-25T07:33:25.273273Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{0: [0.0], 1: [nan]}\n", "Clinical data saved to ../../output/preprocess/Liver_cirrhosis/clinical_data/GSE150734.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background info, this appears to be gene expression data from liver biopsies\n", "# Series title mentions \"Liver Signature profiles\" and overall design mentions \"Gene expression profiling\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# For trait (Liver_cirrhosis), we can infer from \"fibrosis stage\" in the sample characteristics\n", "trait_row = 0 # fibrosis stage is in row 0\n", "\n", "# Age is not available in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# Gender is not available in the sample characteristics dictionary\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert liver fibrosis stage to binary indication of cirrhosis.\n", " In fibrosis staging, stages 0-3 are non-cirrhotic, while stage 4 is cirrhotic.\n", " However, this dataset only shows stages 0 and 1, indicating no cirrhosis.\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after \":\"\n", " if \":\" in value:\n", " stage_str = value.split(\":\")[1].strip()\n", " else:\n", " stage_str = value.strip()\n", " \n", " try:\n", " # Convert to integer\n", " stage = int(stage_str)\n", " # In liver fibrosis staging, stage 4 is cirrhosis\n", " # Stages 0-3 are non-cirrhotic\n", " # This dataset only shows stages 0 and 1\n", " return 1 if stage == 4 else 0 # 1 for cirrhosis, 0 for non-cirrhosis\n", " except ValueError:\n", " return None\n", "\n", "# No conversion functions needed for age and gender as they are not available\n", "convert_age = None\n", "convert_gender = None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info (initial filtering)\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", " # Define clinical_data - use the actual dictionary from the output\n", " sample_characteristics_dict = {0: ['fibrosis stage: 0', 'fibrosis stage: 1'], \n", " 1: ['pls risk prediction: High', 'pls risk prediction: Intermediate', 'pls risk prediction: Low']}\n", " \n", " # Create clinical_data DataFrame with the right structure\n", " clinical_data = pd.DataFrame()\n", " for idx, values in sample_characteristics_dict.items():\n", " clinical_data[idx] = pd.Series(values)\n", " \n", " # Extract 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", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_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", " 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": "4736cdbe", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "f89107f7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:25.274639Z", "iopub.status.busy": "2025-03-25T07:33:25.274538Z", "iopub.status.idle": "2025-03-25T07:33:25.302061Z", "shell.execute_reply": "2025-03-25T07:33:25.301735Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Liver_cirrhosis/GSE150734/GSE150734_series_matrix.txt.gz\n", "Gene data shape: (192, 309)\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": "24de6c96", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "b40fd212", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:25.303122Z", "iopub.status.busy": "2025-03-25T07:33:25.303018Z", "iopub.status.idle": "2025-03-25T07:33:25.304856Z", "shell.execute_reply": "2025-03-25T07:33:25.304551Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers in the gene expression data, these appear to be standard human gene symbols\n", "# (like AARS, ABLIM1, ACOT2, etc.) which are official gene symbols.\n", "# They don't require mapping to different identifiers.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "c6432aed", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "4470ee97", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:25.305922Z", "iopub.status.busy": "2025-03-25T07:33:25.305823Z", "iopub.status.idle": "2025-03-25T07:33:25.478807Z", "shell.execute_reply": "2025-03-25T07:33:25.478473Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (192, 309)\n", "Gene data shape after normalization: (191, 309)\n", "Normalized gene expression data saved to ../../output/preprocess/Liver_cirrhosis/gene_data/GSE150734.csv\n", "Original clinical data preview:\n", " !Sample_geo_accession GSM4557370 \\\n", "0 !Sample_characteristics_ch1 fibrosis stage: 0 \n", "1 !Sample_characteristics_ch1 pls risk prediction: High \n", "\n", " GSM4557371 GSM4557372 \\\n", "0 fibrosis stage: 0 fibrosis stage: 0 \n", "1 pls risk prediction: Intermediate pls risk prediction: Intermediate \n", "\n", " GSM4557373 GSM4557374 \\\n", "0 fibrosis stage: 0 fibrosis stage: 0 \n", "1 pls risk prediction: High pls risk prediction: Intermediate \n", "\n", " GSM4557375 GSM4557376 \\\n", "0 fibrosis stage: 0 fibrosis stage: 0 \n", "1 pls risk prediction: High pls risk prediction: High \n", "\n", " GSM4557377 GSM4557378 ... \\\n", "0 fibrosis stage: 0 fibrosis stage: 0 ... \n", "1 pls risk prediction: Intermediate pls risk prediction: High ... \n", "\n", " GSM4557669 GSM4557670 \\\n", "0 fibrosis stage: 1 fibrosis stage: 0 \n", "1 pls risk prediction: High pls risk prediction: Intermediate \n", "\n", " GSM4557671 GSM4557672 \\\n", "0 fibrosis stage: 0 fibrosis stage: 0 \n", "1 pls risk prediction: Intermediate pls risk prediction: Intermediate \n", "\n", " GSM4557673 GSM4557674 \\\n", "0 fibrosis stage: 0 fibrosis stage: 0 \n", "1 pls risk prediction: Intermediate pls risk prediction: High \n", "\n", " GSM4557675 GSM4557676 \\\n", "0 fibrosis stage: 0 fibrosis stage: 0 \n", "1 pls risk prediction: Intermediate pls risk prediction: Intermediate \n", "\n", " GSM4557677 GSM4557678 \n", "0 fibrosis stage: 1 fibrosis stage: 0 \n", "1 pls risk prediction: Low pls risk prediction: Intermediate \n", "\n", "[2 rows x 310 columns]\n", "Selected clinical data shape: (1, 309)\n", "Clinical data preview:\n", " GSM4557370 GSM4557371 GSM4557372 GSM4557373 GSM4557374 \\\n", "Liver_cirrhosis 0.0 0.0 0.0 0.0 0.0 \n", "\n", " GSM4557375 GSM4557376 GSM4557377 GSM4557378 GSM4557379 \\\n", "Liver_cirrhosis 0.0 0.0 0.0 0.0 0.0 \n", "\n", " ... GSM4557669 GSM4557670 GSM4557671 GSM4557672 \\\n", "Liver_cirrhosis ... 0.0 0.0 0.0 0.0 \n", "\n", " GSM4557673 GSM4557674 GSM4557675 GSM4557676 GSM4557677 \\\n", "Liver_cirrhosis 0.0 0.0 0.0 0.0 0.0 \n", "\n", " GSM4557678 \n", "Liver_cirrhosis 0.0 \n", "\n", "[1 rows x 309 columns]\n", "Linked data shape before processing: (309, 192)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Liver_cirrhosis AARS1 ABLIM1 ACOT2 ACSM3\n", "GSM4557370 0.0 0.881006 0.893351 0.896714 0.926412\n", "GSM4557371 0.0 0.905728 0.882658 0.824298 0.988035\n", "GSM4557372 0.0 0.927254 0.819035 0.880509 0.954744\n", "GSM4557373 0.0 0.927684 0.874450 0.815796 0.882908\n", "GSM4557374 0.0 0.939603 0.847486 0.863436 0.948436\n", "Data shape after handling missing values: (309, 192)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Quartiles for 'Liver_cirrhosis':\n", " 25%: 0.0\n", " 50% (Median): 0.0\n", " 75%: 0.0\n", "Min: 0.0\n", "Max: 0.0\n", "The distribution of the feature 'Liver_cirrhosis' in this dataset is severely biased.\n", "\n", "Data shape after removing biased features: (309, 192)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Dataset is not usable for analysis. No linked data file saved.\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 }