{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "7725dc7a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:00.810983Z", "iopub.status.busy": "2025-03-25T05:43:00.810763Z", "iopub.status.idle": "2025-03-25T05:43:00.982338Z", "shell.execute_reply": "2025-03-25T05:43:00.981983Z" } }, "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 = \"GSE45032\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Hepatitis\"\n", "in_cohort_dir = \"../../input/GEO/Hepatitis/GSE45032\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hepatitis/GSE45032.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hepatitis/gene_data/GSE45032.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hepatitis/clinical_data/GSE45032.csv\"\n", "json_path = \"../../output/preprocess/Hepatitis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "0fa073fe", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0c1a1bbe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:00.983816Z", "iopub.status.busy": "2025-03-25T05:43:00.983664Z", "iopub.status.idle": "2025-03-25T05:43:01.168733Z", "shell.execute_reply": "2025-03-25T05:43:01.168366Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression in liver of HCC and CHC patients\"\n", "!Series_summary\t\"In order to compare age depenpdence of mRNA between HCC and CHC patients, we measured gene expression by microarray.\"\n", "!Series_overall_design\t\"24 liver samples are taken from HCC and CHC patients with various ages and gender.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: hepatocallular carcinoma', 'cell type: chronic hepatitis type C'], 1: ['tissue: liver'], 2: ['gender: male', 'gender: female'], 3: ['age(yrs): 67', 'age(yrs): 56', 'age(yrs): 76', 'age(yrs): 79', 'age(yrs): 66', 'age(yrs): 70', 'age(yrs): 68', 'age(yrs): 72', 'age(yrs): 62', 'age(yrs): 55', 'age(yrs): 71', 'age(yrs): 73', 'age(yrs): 74', 'age(yrs): 61', 'age(yrs): 54', 'age(yrs): 64', 'age(yrs): 59', 'age(yrs): 69', 'age(yrs): 25', 'age(yrs): 41', 'age(yrs): 50', 'age(yrs): 58', 'age(yrs): 49', 'age(yrs): 63', 'age(yrs): 60', 'age(yrs): 52', 'age(yrs): 51']}\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": "7e855105", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "a2d52b00", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:01.169932Z", "iopub.status.busy": "2025-03-25T05:43:01.169820Z", "iopub.status.idle": "2025-03-25T05:43:01.183523Z", "shell.execute_reply": "2025-03-25T05:43:01.183210Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical data: {'Sample_1': [1.0, 67.0, 1.0], 'Sample_2': [0.0, 56.0, 0.0], 'Sample_3': [nan, 76.0, nan], 'Sample_4': [nan, 79.0, nan], 'Sample_5': [nan, 66.0, nan], 'Sample_6': [nan, 70.0, nan], 'Sample_7': [nan, 68.0, nan], 'Sample_8': [nan, 72.0, nan], 'Sample_9': [nan, 62.0, nan], 'Sample_10': [nan, 55.0, nan], 'Sample_11': [nan, 71.0, nan], 'Sample_12': [nan, 73.0, nan], 'Sample_13': [nan, 74.0, nan], 'Sample_14': [nan, 61.0, nan], 'Sample_15': [nan, 54.0, nan], 'Sample_16': [nan, 64.0, nan], 'Sample_17': [nan, 59.0, nan], 'Sample_18': [nan, 69.0, nan], 'Sample_19': [nan, 25.0, nan], 'Sample_20': [nan, 41.0, nan], 'Sample_21': [nan, 50.0, nan], 'Sample_22': [nan, 58.0, nan], 'Sample_23': [nan, 49.0, nan], 'Sample_24': [nan, 63.0, nan], 'Sample_25': [nan, 60.0, nan], 'Sample_26': [nan, 52.0, nan], 'Sample_27': [nan, 51.0, nan]}\n", "Clinical data saved to ../../output/preprocess/Hepatitis/clinical_data/GSE45032.csv\n" ] } ], "source": [ "# Analysis of dataset\n", "# 1. Gene Expression Data Availability\n", "# From the background information, we can see this is a microarray measurement\n", "# of gene expression, so it's likely to contain gene expression data.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For the trait (Hepatitis), looking at key 0, we see \"hepatocallular carcinoma\" and \"chronic hepatitis type C\"\n", "# These are different types of hepatitis conditions, so trait data is available\n", "trait_row = 0\n", "\n", "# Age information is available at key 3\n", "age_row = 3\n", "\n", "# Gender information is available at key 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait data to binary (0 for CHC, 1 for HCC)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"hepatocallular carcinoma\" in value.lower() or \"hcc\" in value.lower():\n", " return 1 # HCC\n", " elif \"chronic hepatitis\" in value.lower() or \"chc\" in value.lower():\n", " return 0 # CHC\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous values\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Extract numeric age value\n", " try:\n", " # Remove 'yrs' or other text and convert to float\n", " age_value = ''.join(c for c in value if c.isdigit() or c == '.')\n", " return float(age_value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary (0 for female, 1 for male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"female\" in value.lower():\n", " return 0\n", " elif \"male\" in value.lower():\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Checking 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", " # Create a sample characteristics dictionary as provided in the output\n", " sample_chars_dict = {\n", " 0: ['cell type: hepatocallular carcinoma', 'cell type: chronic hepatitis type C'], \n", " 1: ['tissue: liver'], \n", " 2: ['gender: male', 'gender: female'], \n", " 3: ['age(yrs): 67', 'age(yrs): 56', 'age(yrs): 76', 'age(yrs): 79', 'age(yrs): 66', \n", " 'age(yrs): 70', 'age(yrs): 68', 'age(yrs): 72', 'age(yrs): 62', 'age(yrs): 55', \n", " 'age(yrs): 71', 'age(yrs): 73', 'age(yrs): 74', 'age(yrs): 61', 'age(yrs): 54', \n", " 'age(yrs): 64', 'age(yrs): 59', 'age(yrs): 69', 'age(yrs): 25', 'age(yrs): 41', \n", " 'age(yrs): 50', 'age(yrs): 58', 'age(yrs): 49', 'age(yrs): 63', 'age(yrs): 60', \n", " 'age(yrs): 52', 'age(yrs): 51']\n", " }\n", " \n", " # Create a DataFrame with sample IDs as columns and characteristics as rows\n", " # This matches the expected format for geo_select_clinical_features\n", " sample_ids = [f\"Sample_{i+1}\" for i in range(max(len(values) for values in sample_chars_dict.values()))]\n", " clinical_data = pd.DataFrame(index=range(max(sample_chars_dict.keys()) + 1), columns=sample_ids)\n", " \n", " # Populate the DataFrame with the available sample characteristics\n", " for row_idx, values in sample_chars_dict.items():\n", " for col_idx, value in enumerate(values):\n", " if col_idx < len(sample_ids):\n", " clinical_data.iloc[row_idx, col_idx] = value\n", " \n", " # Extract clinical features\n", " selected_clinical = 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 data\n", " preview = preview_df(selected_clinical)\n", " print(\"Preview of clinical data:\", preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save to CSV\n", " selected_clinical.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "31c936d4", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "66d8589e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:01.184665Z", "iopub.status.busy": "2025-03-25T05:43:01.184557Z", "iopub.status.idle": "2025-03-25T05:43:01.477276Z", "shell.execute_reply": "2025-03-25T05:43:01.476874Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 62976 rows\n", "First 20 gene IDs:\n", "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n", " '14', '15', '16', '17', '18', '19', '20'],\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": "bdbe0107", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d4c23d7c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:01.478657Z", "iopub.status.busy": "2025-03-25T05:43:01.478532Z", "iopub.status.idle": "2025-03-25T05:43:01.480534Z", "shell.execute_reply": "2025-03-25T05:43:01.480234Z" } }, "outputs": [], "source": [ "# Based on the gene IDs observed, these appear to be numeric identifiers (1, 2, 3, etc.)\n", "# rather than standard human gene symbols (which would look like BRCA1, TP53, IL6, etc.)\n", "# Therefore, gene mapping will be required to convert these numeric IDs to standard gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "d4dbde79", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "c289c33e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:01.481796Z", "iopub.status.busy": "2025-03-25T05:43:01.481688Z", "iopub.status.idle": "2025-03-25T05:43:01.757626Z", "shell.execute_reply": "2025-03-25T05:43:01.757184Z" } }, "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 = GSE45032\n", "Line 6: !Series_title = Gene expression in liver of HCC and CHC patients\n", "Line 7: !Series_geo_accession = GSE45032\n", "Line 8: !Series_status = Public on Dec 21 2023\n", "Line 9: !Series_submission_date = Mar 12 2013\n", "Line 10: !Series_last_update_date = Dec 21 2023\n", "Line 11: !Series_summary = In order to compare age depenpdence of mRNA between HCC and CHC patients, we measured gene expression by microarray.\n", "Line 12: !Series_overall_design = 24 liver samples are taken from HCC and CHC patients with various ages and gender.\n", "Line 13: !Series_type = Expression profiling by array\n", "Line 14: !Series_contributor = Y-h,,Taguchi\n", "Line 15: !Series_contributor = Yoshiki,,Murakami\n", "Line 16: !Series_sample_id = GSM1096016\n", "Line 17: !Series_sample_id = GSM1096017\n", "Line 18: !Series_sample_id = GSM1096018\n", "Line 19: !Series_sample_id = GSM1096019\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': [1, 2, 3, 4, 5], 'ProbeName': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_23_P326296', 'A_24_P287941'], 'GB_ACC': [nan, nan, nan, 'NM_144987', 'NM_013290'], 'ControlType': [1, 1, 1, 0, 0], 'accessions': [nan, nan, nan, 'ref|NM_144987|ref|NM_001040425|ens|ENST00000292879|ens|ENST00000392196', 'ref|NM_013290|ref|NM_016556|ens|ENST00000393795|ens|ENST00000253789'], 'GeneName': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'U2AF1L4', 'PSMC3IP'], 'Description': [nan, nan, nan, 'ref|Homo sapiens U2 small nuclear RNA auxiliary factor 1-like 4 (U2AF1L4), transcript variant 2, mRNA [NM_144987]', 'ref|Homo sapiens PSMC3 interacting protein (PSMC3IP), transcript variant 1, mRNA [NM_013290]'], 'chr_coord': [nan, nan, nan, 'hs|chr19:036235296-036235237', 'hs|chr17:040724775-040724716'], 'SEQUENCE': [nan, nan, nan, 'GTATGGGGAGATTGAAGAGATGAATGTGTGCGACAACCTTGGGGACCACGTCGTGGGCAA', 'AAATTGCAGTAGCTTGAGGTTAACATTTAGACTTGGAACAATGCTAAAGGAAAGCATTTG'], 'SPOT_ID': ['--GE_BrightCorner', '--DarkCorner', '--DarkCorner', nan, nan]}\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": "edbd705e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "be4f5bec", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:01.759196Z", "iopub.status.busy": "2025-03-25T05:43:01.759066Z", "iopub.status.idle": "2025-03-25T05:43:02.508394Z", "shell.execute_reply": "2025-03-25T05:43:02.508014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene ID to symbol mapping...\n", "Created mapping with 62976 entries\n", "First 5 entries of gene mapping:\n", " ID Gene\n", "0 1 GE_BrightCorner\n", "1 2 DarkCorner\n", "2 3 DarkCorner\n", "3 4 U2AF1L4\n", "4 5 PSMC3IP\n", "\n", "Applying gene mapping to convert probe measurements to gene expression...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Converted gene expression data with 20147 unique genes\n", "First 10 gene symbols:\n", "Index(['A1BG', 'A1CF', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT',\n", " 'AA081107', 'AA213559'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Hepatitis/gene_data/GSE45032.csv\n" ] } ], "source": [ "# 1. Based on the gene expression data and gene annotation preview, \n", "# we need to identify the correct columns for mapping\n", "# From the gene expression data, the gene identifiers are numeric (1, 2, 3...)\n", "# From the gene annotation, 'ID' column matches these numeric identifiers, \n", "# and 'GeneName' contains the gene symbols we need\n", "\n", "# 2. Create gene mapping dataframe from annotation data\n", "prob_col = 'ID' # Column containing probe IDs matching gene expression data\n", "gene_col = 'GeneName' # Column containing gene symbols\n", "\n", "# Extract the mapping between ID and GeneName\n", "try:\n", " print(\"Creating gene ID to symbol mapping...\")\n", " gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", " print(f\"Created mapping with {len(gene_mapping)} entries\")\n", " print(\"First 5 entries of gene mapping:\")\n", " print(gene_mapping.head())\n", "except Exception as e:\n", " print(f\"Error creating gene mapping: {e}\")\n", " raise\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n", "try:\n", " print(\"\\nApplying gene mapping to convert probe measurements to gene expression...\")\n", " gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", " print(f\"Converted gene expression data with {len(gene_data.index)} unique genes\")\n", " print(\"First 10 gene symbols:\")\n", " print(gene_data.index[:10])\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", "except Exception as e:\n", " print(f\"Error applying gene mapping: {e}\")\n", " raise\n" ] }, { "cell_type": "markdown", "id": "a8fcacc6", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "27409b72", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:02.509840Z", "iopub.status.busy": "2025-03-25T05:43:02.509713Z", "iopub.status.idle": "2025-03-25T05:43:03.153490Z", "shell.execute_reply": "2025-03-25T05:43:03.153099Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (20147, 48)\n", "Gene data shape after normalization: (19274, 48)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Hepatitis/gene_data/GSE45032.csv\n", "Clinical data saved to ../../output/preprocess/Hepatitis/clinical_data/GSE45032.csv\n", "Linked data shape: (75, 19277)\n", "\n", "Handling missing values...\n", "After missing value handling, linked data shape: (0, 2)\n", "Skipping bias evaluation due to insufficient data.\n", "Abnormality detected in the cohort: GSE45032. Preprocessing failed.\n", "\n", "Dataset usability: False\n", "Dataset is not usable for Hepatitis association studies. Data not saved.\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 }