{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "872d146f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:42:50.951925Z", "iopub.status.busy": "2025-03-25T05:42:50.951746Z", "iopub.status.idle": "2025-03-25T05:42:51.117765Z", "shell.execute_reply": "2025-03-25T05:42:51.117331Z" } }, "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 = \"Hepatitis\"\n", "cohort = \"GSE168049\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Hepatitis\"\n", "in_cohort_dir = \"../../input/GEO/Hepatitis/GSE168049\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hepatitis/GSE168049.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hepatitis/gene_data/GSE168049.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hepatitis/clinical_data/GSE168049.csv\"\n", "json_path = \"../../output/preprocess/Hepatitis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "c14b5bb1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "053afaf7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:42:51.119059Z", "iopub.status.busy": "2025-03-25T05:42:51.118900Z", "iopub.status.idle": "2025-03-25T05:42:51.212469Z", "shell.execute_reply": "2025-03-25T05:42:51.212104Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Prognosis associated mRNA and microRNA in peripheral blood mononuclear cells (PBMCs) from hepatitis B virus-related acute-on-chronic liver failure (HBV-ACLF)\"\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: ['disease: hepatitis B virus-related acute-on-chronic liver failure (HBV-ACLF)'], 1: ['tissue: whole blood'], 2: ['gender: male', 'gender: female'], 3: ['age: 35', 'age: 36', 'age: 57', 'age: 37', 'age: 58', 'age: 53', 'age: 30', 'age: 44', 'age: 69', 'age: 67', 'age: 34', 'age: 55', 'age: 62'], 4: ['survival state of 28-day: survivial', 'survival state of 28-day: dead']}\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": "db915a8e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "30568404", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:42:51.213464Z", "iopub.status.busy": "2025-03-25T05:42:51.213352Z", "iopub.status.idle": "2025-03-25T05:42:51.218466Z", "shell.execute_reply": "2025-03-25T05:42:51.218115Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Dataset Analysis Summary:\n", "- Gene Expression Data Available: True\n", "- Trait Data Available: True\n", "- Age Data Available: True\n", "- Gender Data Available: True\n", "- Trait is in row: 4\n", "- Age is in row: 3\n", "- Gender is in row: 2\n", "Note: The actual clinical data processing will be done in a subsequent step.\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Given the background information, this appears to be a dataset about HBV-ACLF with mRNA data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait: looking at the sample characteristics, key 4 has survival state\n", "trait_row = 4\n", "# For age: key 3 has various ages\n", "age_row = 3\n", "# For gender: key 2 has gender information\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert survival state to binary: 0 for dead, 1 for survival.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = value.lower()\n", " if \"survival state of 28-day:\" in value:\n", " value = value.replace(\"survival state of 28-day:\", \"\").strip()\n", " if \"survivial\" in value or \"survival\" in value:\n", " return 1\n", " elif \"dead\" in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " if \"age:\" in value:\n", " try:\n", " return float(value.split(\"age:\")[1].strip())\n", " except:\n", " return None\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"Convert gender to binary: 0 for female, 1 for male.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " if \"gender:\" in value:\n", " value = value.replace(\"gender:\", \"\").strip().lower()\n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available)\n", "\n", "# 4. Clinical Feature Extraction\n", "# In this step, we're only analyzing the dataset, not processing it.\n", "# Based on the error, accessing clinical_data.csv failed because it doesn't exist.\n", "# We'll skip the actual extraction and save for now, as this step is just for analysis.\n", "\n", "print(f\"Dataset Analysis Summary:\")\n", "print(f\"- Gene Expression Data Available: {is_gene_available}\")\n", "print(f\"- Trait Data Available: {is_trait_available}\")\n", "print(f\"- Age Data Available: {age_row is not None}\")\n", "print(f\"- Gender Data Available: {gender_row is not None}\")\n", "print(f\"- Trait is in row: {trait_row}\")\n", "print(f\"- Age is in row: {age_row}\")\n", "print(f\"- Gender is in row: {gender_row}\")\n", "print(f\"Note: The actual clinical data processing will be done in a subsequent step.\")\n" ] }, { "cell_type": "markdown", "id": "b9fbaca6", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "be1d0d7f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:42:51.219404Z", "iopub.status.busy": "2025-03-25T05:42:51.219300Z", "iopub.status.idle": "2025-03-25T05:42:51.323110Z", "shell.execute_reply": "2025-03-25T05:42:51.322659Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n", "Successfully extracted gene data with 48908 rows\n", "First 20 gene IDs:\n", "Index(['A_19_P00315452', 'A_19_P00315492', 'A_19_P00315493', 'A_19_P00315502',\n", " 'A_19_P00315506', 'A_19_P00315518', 'A_19_P00315529', 'A_19_P00315541',\n", " 'A_19_P00315543', 'A_19_P00315551', 'A_19_P00315581', 'A_19_P00315584',\n", " 'A_19_P00315603', 'A_19_P00315625', 'A_19_P00315627', 'A_19_P00315631',\n", " 'A_19_P00315641', 'A_19_P00315647', 'A_19_P00315649', 'A_19_P00315668'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "3bf9190b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "43166d9c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:42:51.324366Z", "iopub.status.busy": "2025-03-25T05:42:51.324245Z", "iopub.status.idle": "2025-03-25T05:42:51.326450Z", "shell.execute_reply": "2025-03-25T05:42:51.325990Z" } }, "outputs": [], "source": [ "# Analyzing gene identifiers in the dataset\n", "\n", "# The identifiers observed in the gene expression data (e.g., 'A_19_P00315452') \n", "# are Agilent microarray probe IDs, not standard human gene symbols.\n", "# These are probe identifiers from an Agilent microarray platform.\n", "# These identifiers need to be mapped to standard human gene symbols for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "76d2b197", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "44a1821c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:42:51.327770Z", "iopub.status.busy": "2025-03-25T05:42:51.327664Z", "iopub.status.idle": "2025-03-25T05:42:51.853127Z", "shell.execute_reply": "2025-03-25T05:42:51.852473Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n", "Line 0: ^DATABASE = GeoMiame\n", "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n", "Line 2: !Database_institute = NCBI NLM NIH\n", "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "Line 4: !Database_email = geo@ncbi.nlm.nih.gov\n", "Line 5: ^SERIES = GSE168049\n", "Line 6: !Series_title = Prognosis associated mRNA and microRNA in peripheral blood mononuclear cells (PBMCs) from hepatitis B virus-related acute-on-chronic liver failure (HBV-ACLF)\n", "Line 7: !Series_geo_accession = GSE168049\n", "Line 8: !Series_status = Public on May 19 2021\n", "Line 9: !Series_submission_date = Mar 02 2021\n", "Line 10: !Series_last_update_date = May 19 2021\n", "Line 11: !Series_pubmed_id = 33996909\n", "Line 12: !Series_summary = This SuperSeries is composed of the SubSeries listed below.\n", "Line 13: !Series_overall_design = Refer to individual Series\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_type = Non-coding RNA profiling by array\n", "Line 16: !Series_sample_id = GSM5124350\n", "Line 17: !Series_sample_id = GSM5124351\n", "Line 18: !Series_sample_id = GSM5124352\n", "Line 19: !Series_sample_id = GSM5124353\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_001105533', nan], 'GB_ACC': [nan, nan, nan, 'NM_001105533', nan], 'LOCUSLINK_ID': [nan, nan, nan, 79974.0, 54880.0], 'GENE_SYMBOL': [nan, nan, nan, 'CPED1', 'BCOR'], 'GENE_NAME': [nan, nan, nan, 'cadherin-like and PC-esterase domain containing 1', 'BCL6 corepressor'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.189652', nan], 'ENSEMBL_ID': [nan, nan, nan, nan, 'ENST00000378463'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_001105533|gb|AK025639|gb|BC030538|tc|THC2601673', 'ens|ENST00000378463'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'unmapped', 'chr7:120901888-120901947', 'chrX:39909128-39909069'], 'CYTOBAND': [nan, nan, nan, 'hs|7q31.31', 'hs|Xp11.4'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens cadherin-like and PC-esterase domain containing 1 (CPED1), transcript variant 2, mRNA [NM_001105533]', 'BCL6 corepressor [Source:HGNC Symbol;Acc:HGNC:20893] [ENST00000378463]'], 'GO_ID': [nan, nan, nan, 'GO:0005783(endoplasmic reticulum)', 'GO:0000122(negative regulation of transcription from RNA polymerase II promoter)|GO:0000415(negative regulation of histone H3-K36 methylation)|GO:0003714(transcription corepressor activity)|GO:0004842(ubiquitin-protein ligase activity)|GO:0005515(protein binding)|GO:0005634(nucleus)|GO:0006351(transcription, DNA-dependent)|GO:0007507(heart development)|GO:0008134(transcription factor binding)|GO:0030502(negative regulation of bone mineralization)|GO:0031072(heat shock protein binding)|GO:0031519(PcG protein complex)|GO:0035518(histone H2A monoubiquitination)|GO:0042476(odontogenesis)|GO:0042826(histone deacetylase binding)|GO:0044212(transcription regulatory region DNA binding)|GO:0045892(negative regulation of transcription, DNA-dependent)|GO:0051572(negative regulation of histone H3-K4 methylation)|GO:0060021(palate development)|GO:0065001(specification of axis polarity)|GO:0070171(negative regulation of tooth mineralization)'], 'SEQUENCE': [nan, nan, 'AATACATGTTTTGGTAAACACTCGGTCAGAGCACCCTCTTTCTGTGGAATCAGACTGGCA', 'GCTTATCTCACCTAATACAGGGACTATGCAACCAAGAAACTGGAAATAAAAACAAAGATA', 'CATCAAAGCTACGAGAGATCCTACACACCCAGATTTAAAAAATAATAAAAACTTAAGGGC'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'A_21_P0014386', 'A_33_P3396872', 'A_33_P3267760']}\n" ] } ], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "049a22e0", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "46630fc6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:42:51.855031Z", "iopub.status.busy": "2025-03-25T05:42:51.854899Z", "iopub.status.idle": "2025-03-25T05:42:52.277288Z", "shell.execute_reply": "2025-03-25T05:42:52.276644Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using mapping from ID (probe IDs) to GENE_SYMBOL (gene symbols)\n", "Created gene mapping with 48862 entries\n", "First 5 mappings:\n", " ID Gene\n", "3 A_33_P3396872 CPED1\n", "4 A_33_P3267760 BCOR\n", "5 A_32_P194264 CHAC2\n", "6 A_23_P153745 IFI30\n", "10 A_21_P0014180 GPR146\n", "Converted probe-level data to gene-level expression\n", "Original probe count: 48862\n", "Unique gene symbols after mapping: 29222\n", "First 10 gene symbols after mapping:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A1CF-2', 'A1CF-3', 'A2M', 'A2M-1',\n", " 'A2M-AS1', 'A2ML1', 'A2MP1'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved gene expression data to ../../output/preprocess/Hepatitis/gene_data/GSE168049.csv\n" ] } ], "source": [ "# 1. Determine which columns in gene annotation store probe IDs and gene symbols\n", "# Based on the preview, the 'ID' column matches the probe identifiers in the gene expression data\n", "# and 'GENE_SYMBOL' contains the corresponding gene symbols\n", "probe_column = 'ID'\n", "gene_symbol_column = 'GENE_SYMBOL'\n", "\n", "print(f\"Using mapping from {probe_column} (probe IDs) to {gene_symbol_column} (gene symbols)\")\n", "\n", "# 2. Extract the gene mapping dataframe with the two columns\n", "try:\n", " gene_mapping = get_gene_mapping(gene_annotation, prob_col=probe_column, gene_col=gene_symbol_column)\n", " print(f\"Created gene mapping with {len(gene_mapping)} entries\")\n", " print(\"First 5 mappings:\")\n", " print(gene_mapping.head())\n", "except Exception as e:\n", " print(f\"Error creating gene mapping: {e}\")\n", " \n", "# 3. Apply the gene mapping to convert probe-level to gene-level expression\n", "try:\n", " # Apply the gene mapping to convert probe-level measurements to gene expression\n", " gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", " print(f\"Converted probe-level data to gene-level expression\")\n", " print(f\"Original probe count: {len(gene_mapping)}\")\n", " print(f\"Unique gene symbols after mapping: {len(gene_data)}\")\n", " print(\"First 10 gene symbols after mapping:\")\n", " print(gene_data.index[:10])\n", " \n", " # Save the gene expression data for later use\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Saved gene expression data to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error applying gene mapping: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "e4470222", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "df76d12b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:42:52.279253Z", "iopub.status.busy": "2025-03-25T05:42:52.279097Z", "iopub.status.idle": "2025-03-25T05:42:59.909906Z", "shell.execute_reply": "2025-03-25T05:42:59.909237Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (29222, 16)\n", "Gene data shape after normalization: (20778, 16)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Hepatitis/gene_data/GSE168049.csv\n", "Clinical data saved to ../../output/preprocess/Hepatitis/clinical_data/GSE168049.csv\n", "Linked data shape: (16, 20781)\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After missing value handling, linked data shape: (16, 20781)\n", "\n", "Evaluating feature bias...\n", "For the feature 'Hepatitis', the least common label is '1.0' with 8 occurrences. This represents 50.00% of the dataset.\n", "The distribution of the feature 'Hepatitis' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 36.0\n", " 50% (Median): 54.0\n", " 75%: 59.0\n", "Min: 30.0\n", "Max: 69.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 3 occurrences. This represents 18.75% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Trait bias evaluation result: False\n", "\n", "Dataset usability: True\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Hepatitis/GSE168049.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols and extract from step 3 and 6\n", "# Load the gene expression data (already loaded from Step 6)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "\n", "try:\n", " # Normalize gene symbols using the NCBI Gene database information\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " \n", " if normalized_gene_data.empty:\n", " print(\"Normalization resulted in empty dataframe. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " \n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data to the output 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 data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " # Save the original gene data if normalization fails\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", "\n", "# 2. Link clinical and genetic data\n", "# Use the trait_row identified in Step 2 (trait_row = 1) to extract trait data\n", "is_trait_available = trait_row is not None\n", "\n", "if is_trait_available:\n", " # Extract clinical features using the function and conversion methods from Step 2\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", " # Save clinical features\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", "else:\n", " # Create a minimal dataframe with just the trait column\n", " linked_data = pd.DataFrame({trait: [np.nan]})\n", " print(\"No trait data available, creating minimal dataframe for validation.\")\n", "\n", "# 3. Handle missing values in the linked data\n", "if is_trait_available:\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After missing value handling, linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Determine whether trait and demographic features are biased\n", "if is_trait_available and not linked_data.empty and len(linked_data.columns) > 1:\n", " print(\"\\nEvaluating feature bias...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Trait bias evaluation result: {is_biased}\")\n", "else:\n", " is_biased = False\n", " print(\"Skipping bias evaluation due to insufficient data.\")\n", "\n", "# 5. Final validation and save metadata\n", "note = \"\"\n", "if not is_trait_available:\n", " note = f\"Dataset contains gene expression data but no {trait} measurements.\"\n", "elif is_biased:\n", " note = f\"Dataset contains {trait} data but its distribution is severely biased.\"\n", "\n", "# Validate and save cohort info\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 usable\n", "print(f\"\\nDataset usability: {is_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(f\"Dataset is not usable for {trait} association studies. Data not 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 }