{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "b8dfa07b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:57:00.202194Z", "iopub.status.busy": "2025-03-25T03:57:00.202085Z", "iopub.status.idle": "2025-03-25T03:57:00.381562Z", "shell.execute_reply": "2025-03-25T03:57:00.381205Z" } }, "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 = \"Sickle_Cell_Anemia\"\n", "cohort = \"GSE46471\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Sickle_Cell_Anemia\"\n", "in_cohort_dir = \"../../input/GEO/Sickle_Cell_Anemia/GSE46471\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Sickle_Cell_Anemia/GSE46471.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Sickle_Cell_Anemia/gene_data/GSE46471.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Sickle_Cell_Anemia/clinical_data/GSE46471.csv\"\n", "json_path = \"../../output/preprocess/Sickle_Cell_Anemia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3206edb3", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "f0dfbc7d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:57:00.383198Z", "iopub.status.busy": "2025-03-25T03:57:00.383042Z", "iopub.status.idle": "2025-03-25T03:57:00.486537Z", "shell.execute_reply": "2025-03-25T03:57:00.486216Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Mechanisms of haptoglobin protection against hemoglobin peroxidation triggered endothelial damage\"\n", "!Series_summary\t\"Extracellular hemoglobin (Hb) has been recognized as a disease trigger in hemolytic conditions such as sickle cell disease, malaria and blood transfusion. In vivo, many of the adverse effects of free Hb can be attenuated by the Hb scavenger acute phase protein haptoglobin (Hp). The primary physiologic disturbances that can be caused be free Hb are found within the cardiovascular system and Hb triggered oxidative toxicity towards the endothelium has been promoted as a potential mechanism. The molecular mechanisms of this toxicity as well as of the protective activities of Hp are not yet clear. Within this study we systematically investigated the structural, biochemical and cell biologic nature of Hb toxicity in an endothelial cell system under peroxidative stress.\"\n", "!Series_summary\t\"We identified two principal mechanisms of oxidative Hb toxicity that are mediated by globin degradation products and by modified lipoprotein species, respectively. The two damage pathways trigger diverse and discriminative inflammatory and cytotoxic responses. Hp provides structural stabilization of Hb and shields Hb’s oxidative reactions with lipoproteins providing dramatic protection against both pathways of toxicity. By these mechanisms Hp shifts Hb’s destructive pseudo-peroxidative reaction into a potential anti-oxidative function during peroxidative stress.\"\n", "!Series_overall_design\t\"HPAEC: A two color common reference design was chosen with 4-8 independent biological replicates of each condition. Each experimental sample (Cy5 labeled) was hybridized against a non-treated reference sample (Cy3 labeled).\"\n", "!Series_overall_design\t\"HUVEC: A two color common reference design was chosen with 3-4 independent biological replicates of each condition. Each experimental sample (Cy5 labeled) was hybridized against a non-treated reference sample (Cy3 labeled).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: HPAEC', 'cell type: HUVEC'], 1: ['treatment: no treatment'], 2: ['time: 0h']}\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": "c153bf0a", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "cdb546c1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:57:00.487676Z", "iopub.status.busy": "2025-03-25T03:57:00.487569Z", "iopub.status.idle": "2025-03-25T03:57:00.493651Z", "shell.execute_reply": "2025-03-25T03:57:00.493383Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "import pandas as pd\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "import numpy as np\n", "\n", "# 1. Gene Expression Data Availability\n", "# From the background information, this dataset is about protein and cellular processes,\n", "# likely containing gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Sickle Cell Anemia):\n", "# The dataset doesn't explicitly show which samples have sickle cell anemia\n", "# The study is about haptoglobin protection against hemoglobin peroxidation, which is related to sickle cell anemia\n", "# But we don't see a clear variable for it in the sample characteristics\n", "trait_row = None\n", "\n", "# For age:\n", "# No age information is provided in the sample characteristics\n", "age_row = None\n", "\n", "# For gender:\n", "# No gender information is provided in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait data to binary (0/1)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # This is a placeholder since trait_row is None in this dataset\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous numeric values\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # This is a placeholder since age_row is None in this dataset\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary (0=female, 1=male)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # This is a placeholder since gender_row is None 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", "# Save initial filtering metadata\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", "# Since trait_row is None, we skip this substep\n" ] }, { "cell_type": "markdown", "id": "101748d6", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "0e6fa070", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:57:00.494664Z", "iopub.status.busy": "2025-03-25T03:57:00.494565Z", "iopub.status.idle": "2025-03-25T03:57:00.672338Z", "shell.execute_reply": "2025-03-25T03:57:00.672005Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 67\n", "Header line: \"ID_REF\"\t\"GSM1130756\"\t\"GSM1130757\"\t\"GSM1130758\"\t\"GSM1130759\"\t\"GSM1130760\"\t\"GSM1130761\"\t\"GSM1130762\"\t\"GSM1130763\"\t\"GSM1130764\"\t\"GSM1130765\"\t\"GSM1130766\"\t\"GSM1130767\"\t\"GSM1130768\"\t\"GSM1130769\"\t\"GSM1130770\"\t\"GSM1130771\"\t\"GSM1130772\"\t\"GSM1130773\"\t\"GSM1130774\"\t\"GSM1130775\"\t\"GSM1130776\"\t\"GSM1130777\"\t\"GSM1130778\"\t\"GSM1130779\"\t\"GSM1130780\"\t\"GSM1130781\"\t\"GSM1130782\"\t\"GSM1130783\"\t\"GSM1130784\"\t\"GSM1130785\"\t\"GSM1130786\"\t\"GSM1130787\"\t\"GSM1130788\"\t\"GSM1130789\"\t\"GSM1130790\"\t\"GSM1130791\"\t\"GSM1130792\"\t\"GSM1130793\"\t\"GSM1130794\"\t\"GSM1130795\"\t\"GSM1130796\"\t\"GSM1130797\"\t\"GSM1130798\"\t\"GSM1130799\"\t\"GSM1130800\"\n", "First data line: 1\t-3.04E-02\t-7.44E-02\t2.51E-02\t4.59E-02\t1.32E-02\t-3.86E-01\t1.63E-03\t1.35E-01\t2.90E-02\t-2.74E-01\t4.99E-02\t1.31E-01\t1.85E-01\t5.61E-02\t-1.69E-02\t-1.39E-01\t-1.33E-01\t1.85E-01\t2.19E-01\t2.12E-01\t2.51E-01\t3.07E-01\t1.25E-01\t2.12E-02\t7.70E-02\t3.12E-01\t1.26E-03\t-6.42E-02\t3.38E-02\t8.79E-02\t2.62E-01\t-6.44E-02\t7.47E-03\t-3.78E-02\t1.43E-01\t2.37E-02\t-1.54E-01\t1.68E-01\t5.48E-02\t4.49E-03\t3.52E-02\t7.06E-02\t1.49E-03\t-5.00E-03\t-4.30E-02\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" ] } ], "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. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "28390034", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "5f3ef9f7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:57:00.673687Z", "iopub.status.busy": "2025-03-25T03:57:00.673573Z", "iopub.status.idle": "2025-03-25T03:57:00.675427Z", "shell.execute_reply": "2025-03-25T03:57:00.675155Z" } }, "outputs": [], "source": [ "# The identifiers in the gene expression data are numeric IDs (1, 2, 3, etc.), which are likely\n", "# probe identifiers from a microarray. These are not human gene symbols and need to be mapped.\n", "# Numeric IDs like this typically correspond to positions on a microarray chip and need to be\n", "# mapped to actual gene symbols using platform annotation files.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "994b2d9a", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "4c2bcd0b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:57:00.676543Z", "iopub.status.busy": "2025-03-25T03:57:00.676445Z", "iopub.status.idle": "2025-03-25T03:57:01.072125Z", "shell.execute_reply": "2025-03-25T03:57:01.071766Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "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 = GSE46471\n", "Line 6: !Series_title = Mechanisms of haptoglobin protection against hemoglobin peroxidation triggered endothelial damage\n", "Line 7: !Series_geo_accession = GSE46471\n", "Line 8: !Series_status = Public on Apr 30 2015\n", "Line 9: !Series_submission_date = Apr 29 2013\n", "Line 10: !Series_last_update_date = Feb 22 2018\n", "Line 11: !Series_pubmed_id = 23995229\n", "Line 12: !Series_summary = Extracellular hemoglobin (Hb) has been recognized as a disease trigger in hemolytic conditions such as sickle cell disease, malaria and blood transfusion. In vivo, many of the adverse effects of free Hb can be attenuated by the Hb scavenger acute phase protein haptoglobin (Hp). The primary physiologic disturbances that can be caused be free Hb are found within the cardiovascular system and Hb triggered oxidative toxicity towards the endothelium has been promoted as a potential mechanism. The molecular mechanisms of this toxicity as well as of the protective activities of Hp are not yet clear. Within this study we systematically investigated the structural, biochemical and cell biologic nature of Hb toxicity in an endothelial cell system under peroxidative stress.\n", "Line 13: !Series_summary = We identified two principal mechanisms of oxidative Hb toxicity that are mediated by globin degradation products and by modified lipoprotein species, respectively. The two damage pathways trigger diverse and discriminative inflammatory and cytotoxic responses. Hp provides structural stabilization of Hb and shields Hb’s oxidative reactions with lipoproteins providing dramatic protection against both pathways of toxicity. By these mechanisms Hp shifts Hb’s destructive pseudo-peroxidative reaction into a potential anti-oxidative function during peroxidative stress.\n", "Line 14: !Series_overall_design = HPAEC: A two color common reference design was chosen with 4-8 independent biological replicates of each condition. Each experimental sample (Cy5 labeled) was hybridized against a non-treated reference sample (Cy3 labeled).\n", "Line 15: !Series_overall_design = HUVEC: A two color common reference design was chosen with 3-4 independent biological replicates of each condition. Each experimental sample (Cy5 labeled) was hybridized against a non-treated reference sample (Cy3 labeled).\n", "Line 16: !Series_type = Expression profiling by array\n", "Line 17: !Series_contributor = Christian,A,Schaer\n", "Line 18: !Series_contributor = Dominik,J,Schaer\n", "Line 19: !Series_sample_id = GSM1130756\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': [1, 2, 3, 4, 5], 'COL': [266, 266, 266, 266, 266], 'ROW': [170, 168, 166, 164, 162], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'SPOT_ID': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner', 'DarkCorner'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan], 'SPOT_ID.1': [nan, nan, nan, nan, nan], 'ORDER': [1, 2, 3, 4, 5]}\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": "986050ca", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "6eba0d98", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:57:01.073546Z", "iopub.status.busy": "2025-03-25T03:57:01.073435Z", "iopub.status.idle": "2025-03-25T03:57:01.551292Z", "shell.execute_reply": "2025-03-25T03:57:01.550962Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data after mapping:\n", "Shape: (18379, 45)\n", "First few gene symbols: ['A1BG', 'A1CF', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS']\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_13897/1685547521.py:12: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n", " mapping_df['ID'] = mapping_df['ID'].astype(str)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to: ../../output/preprocess/Sickle_Cell_Anemia/gene_data/GSE46471.csv\n", "Abnormality detected in the cohort: GSE46471. Preprocessing failed.\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 1. Observe the gene identifiers and annotation data\n", "# From previous analysis:\n", "# - Gene expression data has numeric IDs (1, 2, 3, etc.)\n", "# - Gene annotation data has columns for ID and GENE_SYMBOL\n", "\n", "# 2. Extract the columns for mapping\n", "# The ID field in the gene annotation corresponds to the gene identifiers in expression data\n", "# The GENE_SYMBOL field contains the gene symbols we want to map to\n", "mapping_df = gene_annotation[['ID', 'GENE_SYMBOL']]\n", "\n", "# Convert ID to string to match the format in gene_data\n", "mapping_df['ID'] = mapping_df['ID'].astype(str)\n", "\n", "# Rename 'GENE_SYMBOL' to 'Gene' as required by apply_gene_mapping function\n", "mapping_df = mapping_df.rename(columns={'GENE_SYMBOL': 'Gene'})\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n", "# We'll use the library function that handles the many-to-many mapping correctly\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Preview the gene data to verify the mapping worked\n", "print(\"Gene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(f\"First few gene symbols: {list(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", "\n", "# Update the metadata to mark the dataset as not usable\n", "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=True, # We don't have trait data, so mark as biased\n", " df=pd.DataFrame(), # Empty dataframe since we can't proceed without trait data\n", " note=\"Dataset contains gene expression data but lacks trait information for Sickle Cell Anemia\"\n", ")\n" ] }, { "cell_type": "markdown", "id": "a4cb788e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "8936aec4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:57:01.552695Z", "iopub.status.busy": "2025-03-25T03:57:01.552581Z", "iopub.status.idle": "2025-03-25T03:57:02.005500Z", "shell.execute_reply": "2025-03-25T03:57:02.005170Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (18379, 45)\n", "Gene data shape after normalization: (17901, 45)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Sickle_Cell_Anemia/gene_data/GSE46471.csv\n", "Trait row is None. Cannot extract trait information from clinical data.\n", "Abnormality detected in the cohort: GSE46471. Preprocessing failed.\n", "Data was determined to be unusable due to missing trait indicators and was not saved\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "\n", "# Normalize gene symbols using NCBI Gene database\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data\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", "\n", "# 2. Check if trait data is available before proceeding with clinical data extraction\n", "if trait_row is None:\n", " print(\"Trait row is None. Cannot extract trait information from clinical data.\")\n", " # Create an empty dataframe for clinical features\n", " clinical_features = pd.DataFrame()\n", " \n", " # Create an empty dataframe for linked data\n", " linked_data = pd.DataFrame()\n", " \n", " # Validate and save cohort info\n", " 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, # Trait data is not available\n", " is_biased=True, # Not applicable but required\n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Dataset contains gene expression data but lacks clear trait indicators for {trait} status.\"\n", " )\n", " print(\"Data was determined to be unusable due to missing trait indicators and was not saved\")\n", "else:\n", " try:\n", " # Get the file paths for the matrix file to extract clinical data\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get raw clinical data from the matrix file\n", " _, clinical_raw = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify clinical data structure\n", " print(\"Raw clinical data shape:\", clinical_raw.shape)\n", " \n", " # Extract clinical features using the defined conversion functions\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_raw,\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(\"Clinical features:\")\n", " print(clinical_features)\n", " \n", " # Save clinical features to file\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 features saved to {out_clinical_data_file}\")\n", " \n", " # 3. 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", " print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing values before handling:\")\n", " print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", " if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", " if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", " \n", " gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n", " print(f\" Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n", " \n", " cleaned_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", " \n", " # 5. Evaluate bias in trait and demographic features\n", " is_trait_biased = False\n", " if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", " else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", " \n", " # 6. Final validation and save\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_trait_biased, \n", " df=cleaned_data,\n", " note=f\"Dataset contains gene expression data for {trait} analysis.\"\n", " )\n", " \n", " # 7. Save if usable\n", " if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # Handle the error case by still recording cohort info\n", " 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, # Mark as not available due to processing issues\n", " is_biased=True, \n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Error processing data for {trait}: {str(e)}\"\n", " )\n", " print(\"Data was determined to be unusable and was 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 }