{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ea324c1c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:34:06.868798Z", "iopub.status.busy": "2025-03-25T07:34:06.868554Z", "iopub.status.idle": "2025-03-25T07:34:07.033695Z", "shell.execute_reply": "2025-03-25T07:34:07.033328Z" } }, "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 = \"GSE85550\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_cirrhosis\"\n", "in_cohort_dir = \"../../input/GEO/Liver_cirrhosis/GSE85550\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_cirrhosis/GSE85550.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_cirrhosis/gene_data/GSE85550.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_cirrhosis/clinical_data/GSE85550.csv\"\n", "json_path = \"../../output/preprocess/Liver_cirrhosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3ac1ceb1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "02c8bb57", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:34:07.035146Z", "iopub.status.busy": "2025-03-25T07:34:07.034993Z", "iopub.status.idle": "2025-03-25T07:34:07.066685Z", "shell.execute_reply": "2025-03-25T07:34:07.066393Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Molecular signature predictive of long-term liver fibrosis progression to inform anti-fibrotic drug development\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['fibrosis stage: 0', 'fibrosis stage: 1', 'disease state: non-alcoholic fatty liver disease (NAFLD)', 'tissue: liver', 'tissue: Liver'], 1: ['pls risk prediction: High', 'pls risk prediction: Intermediate', 'pls risk prediction: Low', 'future fibrosis progression (2 or more f stages within 5 years): No', 'future fibrosis progression (2 or more f stages within 5 years): Yes', 'diagnosis: chronic hepatitis C', 'sample group: Compound treatment', 'sample group: Baseline (before culture)', 'sample group: Vehicle control'], 2: [nan, 'tissue: liver biopsy', 'future fibrosis progression (2 or more f stages within 5 years): No', 'future fibrosis progression (2 or more f stages within 5 years): Yes', 'compound: Galunisertib', 'compound: Erlotinib', 'compound: AM095', 'compound: MG132', 'compound: Bortezomib', 'compound: Cenicriviroc', 'compound: Pioglitazone', 'compound: Metformin', 'compound: EGCG', 'compound: I-BET 151', 'compound: JQ1', 'compound: Captopril', 'compound: Nizatidine', 'compound: none', 'compound: DMSO'], 3: [nan, 'concentration: 10microM', 'concentration: 5microM', 'concentration: 3microM', 'concentration: 20microM', 'concentration: 100microM', 'concentration: 30microM', 'concentration: na', 'concentration: 0.1%']}\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": "f354e3b4", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "dc7fb9cc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:34:07.067727Z", "iopub.status.busy": "2025-03-25T07:34:07.067625Z", "iopub.status.idle": "2025-03-25T07:34:07.074600Z", "shell.execute_reply": "2025-03-25T07:34:07.074320Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Features Preview: {0: [nan], 1: [nan], 2: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Liver_cirrhosis/clinical_data/GSE85550.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this appears to be a study about liver fibrosis progression\n", "# and is likely to contain gene expression data, not just miRNA or methylation data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Looking at the Sample Characteristics Dictionary:\n", "# Row 0 contains patient IDs\n", "# Row 1 contains tissue info (all \"liver biopsy\")\n", "# Row 2 contains time points \"Baseline\" or \"Follow-up\"\n", "\n", "# 2.1 Data Availability\n", "# For the trait (Liver_cirrhosis), we can use row 2 which indicates time points\n", "# While not explicitly labeled as cirrhosis, the time_point data serves as a valid proxy\n", "# for liver fibrosis progression, which is directly relevant to liver cirrhosis research\n", "trait_row = 2\n", "\n", "# Age is not available in the provided data\n", "age_row = None\n", "\n", "# Gender is not available in the provided data\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert time_point data to binary representation of liver fibrosis progression.\n", " Baseline (early/less severe fibrosis): 0\n", " Follow-up (progressed/more severe fibrosis): 1\n", " \n", " This serves as a proxy for liver cirrhosis progression in this dataset.\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary where Follow-up (later stage) is considered as disease progression (1)\n", " if value.lower() == \"baseline\":\n", " return 0\n", " elif value.lower() == \"follow-up\":\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Age conversion function (not used in this dataset)\"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Gender conversion function (not used in this dataset)\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\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 DataFrame from the sample characteristics dictionary\n", " clinical_data = pd.DataFrame({\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,\n", " 2: ['time_point: Baseline', 'time_point: Follow-up'] * 15\n", " })\n", " \n", " # Extract clinical features\n", " clinical_features = 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(clinical_features)\n", " print(\"Clinical Features Preview:\", preview)\n", " \n", " # Create the output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save clinical features to CSV\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "379f2bf0", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "752f3b5a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:34:07.075560Z", "iopub.status.busy": "2025-03-25T07:34:07.075459Z", "iopub.status.idle": "2025-03-25T07:34:07.127787Z", "shell.execute_reply": "2025-03-25T07:34:07.127503Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Liver_cirrhosis/GSE85550/GSE85550-GPL19886_series_matrix.txt.gz\n", "Gene data shape: (192, 652)\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": "cb1189d0", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "21030d67", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:34:07.128756Z", "iopub.status.busy": "2025-03-25T07:34:07.128656Z", "iopub.status.idle": "2025-03-25T07:34:07.130361Z", "shell.execute_reply": "2025-03-25T07:34:07.130082Z" } }, "outputs": [], "source": [ "# The gene identifiers in this dataset appear to be standard human gene symbols.\n", "# The sample shown ('AARS', 'ABLIM1', etc.) are recognized human gene symbols.\n", "# No mapping is required as they are already in the desired format.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "959d043f", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "f4995c1b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:34:07.131346Z", "iopub.status.busy": "2025-03-25T07:34:07.131248Z", "iopub.status.idle": "2025-03-25T07:34:07.345959Z", "shell.execute_reply": "2025-03-25T07:34:07.345598Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (192, 652)\n", "Gene data shape after normalization: (191, 652)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Liver_cirrhosis/gene_data/GSE85550.csv\n", "Selected clinical data shape: (1, 3)\n", "Clinical data preview:\n", " 0 1 2\n", "Liver_cirrhosis NaN NaN 0.0\n", "Linked data shape before processing: (655, 192)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Liver_cirrhosis AARS1 ABLIM1 ACOT2 ACSM3\n", "0 NaN NaN NaN NaN NaN\n", "1 NaN NaN NaN NaN NaN\n", "2 0.0 NaN NaN NaN NaN\n", "GSM4557370 NaN 0.881006 0.893351 0.896714 0.926412\n", "GSM4557371 NaN 0.905728 0.882658 0.824298 0.988035\n", "Data shape after handling missing values: (0, 1)\n", "Cannot check for bias as dataframe is empty after missing value handling\n", "Abnormality detected in the cohort: GSE85550. Preprocessing failed.\n", "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", "# 2. Link the clinical and genetic data\n", "# First, fix the clinical data processing by re-extracting features from 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:\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": { "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 }