{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "7bbe7ed2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:26.912742Z", "iopub.status.busy": "2025-03-25T07:27:26.912524Z", "iopub.status.idle": "2025-03-25T07:27:27.070166Z", "shell.execute_reply": "2025-03-25T07:27:27.069830Z" } }, "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 = \"LDL_Cholesterol_Levels\"\n", "cohort = \"GSE111567\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/LDL_Cholesterol_Levels\"\n", "in_cohort_dir = \"../../input/GEO/LDL_Cholesterol_Levels/GSE111567\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/LDL_Cholesterol_Levels/GSE111567.csv\"\n", "out_gene_data_file = \"../../output/preprocess/LDL_Cholesterol_Levels/gene_data/GSE111567.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/LDL_Cholesterol_Levels/clinical_data/GSE111567.csv\"\n", "json_path = \"../../output/preprocess/LDL_Cholesterol_Levels/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "aa596749", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "fe1e6499", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:27.071565Z", "iopub.status.busy": "2025-03-25T07:27:27.071431Z", "iopub.status.idle": "2025-03-25T07:27:27.156034Z", "shell.execute_reply": "2025-03-25T07:27:27.155736Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Plasma fatty acid levels and gene expression related to lipid metabolism in peripheral blood mononuclear cells\"\n", "!Series_summary\t\"Solid evidence indicates that intake of marine n-3 fatty acids lower serum triglycerides, and that replacing saturated fatty acids (SFA) with polyunsaturated fatty acids (PUFA) reduces plasma total cholesterol and LDL-cholesterol. The molecular mechanisms underlying these health beneficial effects are however not completely elucidated. The aim of this study was to investigate the expression of genes related to lipid metabolism in peripheral blood mononuclear cells (PBMC) depending on the plasma levels of n-6 and n-3 fatty acids and the SFA to PUFA ratio.\"\n", "!Series_overall_design\t\"This study is a cross-sectional sub-study of a randomised controlled trial designed to investigate the health effects of fish oil intake (Ottestad el al, 2012, Myhrstad et al, 2014). The study population was grouped into tertiles three times according to the plasma fatty acid levels of n-6 and n-3 fatty acids and the plasma SFA to PUFA ratio at the end of study by arranging samples from the highest to the lowest value. Peripheral blood monnucelar cell gene expression between subjects in the highest (n=18) and the lowest (n=18) tertile within each arrangement in groups were further compared. A total of 285 genes encoding proteins related to cholesterol and triglyceride metabolism were selected for this explorative analysis. 161 genes were defined as expressed on the HumanHT-12 v4 microarray and included in the statistical analyses.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: M', 'gender: F'], 1: ['tissue: Peripheral blood mononuclear cells'], 2: ['n6 level tertiles (1=low, 2=middle, 3=high): 2', 'n6 level tertiles (1=low, 2=middle, 3=high): 3', 'n6 level tertiles (1=low, 2=middle, 3=high): 1'], 3: ['n3 level tertiles (1=low, 2=middle, 3=high): 1', 'n3 level tertiles (1=low, 2=middle, 3=high): 2', 'n3 level tertiles (1=low, 2=middle, 3=high): 3'], 4: ['sfa/pufa ratio tertiles (1=low, 2=middle, 3=high): 2', 'sfa/pufa ratio tertiles (1=low, 2=middle, 3=high): 3', 'sfa/pufa ratio tertiles (1=low, 2=middle, 3=high): 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": "bbe467f2", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9dc8c66f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:27.157102Z", "iopub.status.busy": "2025-03-25T07:27:27.156994Z", "iopub.status.idle": "2025-03-25T07:27:27.173440Z", "shell.execute_reply": "2025-03-25T07:27:27.173169Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A new JSON file was created at: ../../output/preprocess/LDL_Cholesterol_Levels/cohort_info.json\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "import re\n", "from typing import Optional, Callable, Dict, Any, List\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from PBMCs\n", "# using HumanHT-12 v4 microarray, which is suitable for our analysis.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (LDL_Cholesterol_Levels):\n", "# The background mentions that this study looked at lipid metabolism,\n", "# but there's no direct LDL measurement in the sample characteristics.\n", "# The study focuses on fatty acid levels (n-6, n-3) and SFA/PUFA ratio.\n", "# Since the study is about \"lipid metabolism\" but no direct LDL values are provided,\n", "# we'll consider it not available.\n", "trait_row = None\n", "\n", "# For age:\n", "# Age is not mentioned in the sample characteristics.\n", "age_row = None\n", "\n", "# For gender:\n", "# Gender information is available at index 0\n", "gender_row = 0\n", "\n", "# 2.2 Data Type Conversion\n", "# Since trait data is not available, we'll define a placeholder function\n", "def convert_trait(value):\n", " return None\n", "\n", "# Age conversion function (placeholder)\n", "def convert_age(value):\n", " return None\n", "\n", "# Gender conversion function\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value:\n", " gender = value.split(':', 1)[1].strip().upper()\n", " if gender == 'F':\n", " return 0 # Female\n", " elif gender == 'M':\n", " return 1 # Male\n", " return None\n", "\n", "# 3. Save Metadata\n", "# The trait data is not available (trait_row is None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering and save 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 should skip this step\n", "if trait_row is not None:\n", " # This code would only run if trait data were available\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, 'clinical_data.csv'))\n", " \n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the DataFrame\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the processed clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n" ] }, { "cell_type": "markdown", "id": "ea6111a4", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "44821f3b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:27.174533Z", "iopub.status.busy": "2025-03-25T07:27:27.174432Z", "iopub.status.idle": "2025-03-25T07:27:27.307071Z", "shell.execute_reply": "2025-03-25T07:27:27.306645Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Plasma fatty acid levels and gene expression related to lipid metabolism in peripheral blood mononuclear cells\"\n", "Line 1: !Series_geo_accession\t\"GSE111567\"\n", "Line 2: !Series_status\t\"Public on Mar 08 2019\"\n", "Line 3: !Series_submission_date\t\"Mar 08 2018\"\n", "Line 4: !Series_last_update_date\t\"Jul 29 2019\"\n", "Line 5: !Series_pubmed_id\t\"29662553\"\n", "Line 6: !Series_summary\t\"Solid evidence indicates that intake of marine n-3 fatty acids lower serum triglycerides, and that replacing saturated fatty acids (SFA) with polyunsaturated fatty acids (PUFA) reduces plasma total cholesterol and LDL-cholesterol. The molecular mechanisms underlying these health beneficial effects are however not completely elucidated. The aim of this study was to investigate the expression of genes related to lipid metabolism in peripheral blood mononuclear cells (PBMC) depending on the plasma levels of n-6 and n-3 fatty acids and the SFA to PUFA ratio.\"\n", "Line 7: !Series_overall_design\t\"This study is a cross-sectional sub-study of a randomised controlled trial designed to investigate the health effects of fish oil intake (Ottestad el al, 2012, Myhrstad et al, 2014). The study population was grouped into tertiles three times according to the plasma fatty acid levels of n-6 and n-3 fatty acids and the plasma SFA to PUFA ratio at the end of study by arranging samples from the highest to the lowest value. Peripheral blood monnucelar cell gene expression between subjects in the highest (n=18) and the lowest (n=18) tertile within each arrangement in groups were further compared. A total of 285 genes encoding proteins related to cholesterol and triglyceride metabolism were selected for this explorative analysis. 161 genes were defined as expressed on the HumanHT-12 v4 microarray and included in the statistical analyses.\"\n", "Line 8: !Series_type\t\"Expression profiling by array\"\n", "Line 9: !Series_contributor\t\"Sunniva,V,Larsen\"\n", "Found table marker at line 67\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM3034383\"\t\"GSM3034384\"\t\"GSM3034385\"\t\"GSM3034386\"\t\"GSM3034387\"\t\"GSM3034388\"\t\"GSM3034389\"\t\"GSM3034390\"\t\"GSM3034391\"\t\"GSM3034392\"\t\"GSM3034393\"\t\"GSM3034394\"\t\"GSM3034395\"\t\"GSM3034396\"\t\"GSM3034397\"\t\"GSM3034398\"\t\"GSM3034399\"\t\"GSM3034400\"\t\"GSM3034401\"\t\"GSM3034402\"\t\"GSM3034403\"\t\"GSM3034404\"\t\"GSM3034405\"\t\"GSM3034406\"\t\"GSM3034407\"\t\"GSM3034408\"\t\"GSM3034409\"\t\"GSM3034410\"\t\"GSM3034411\"\t\"GSM3034412\"\t\"GSM3034413\"\t\"GSM3034414\"\t\"GSM3034415\"\t\"GSM3034416\"\t\"GSM3034417\"\t\"GSM3034418\"\t\"GSM3034419\"\t\"GSM3034420\"\t\"GSM3034421\"\t\"GSM3034422\"\t\"GSM3034423\"\t\"GSM3034424\"\t\"GSM3034425\"\t\"GSM3034426\"\t\"GSM3034427\"\t\"GSM3034428\"\t\"GSM3034429\"\t\"GSM3034430\"\t\"GSM3034431\"\t\"GSM3034432\"\t\"GSM3034433\"\t\"GSM3034434\"\t\"GSM3034435\"\t\"GSM3034436\"\n", "\"ILMN_1343291\"\t14.1752257\t14.13688086\t14.06270747\t14.218206\t14.1752257\t14.16038301\t14.12724543\t14.25540728\t14.25540728\t14.13688086\t14.13688086\t14.19395081\t14.25540728\t14.13688086\t14.218206\t14.218206\t14.1752257\t14.1091584\t14.10086726\t14.218206\t14.218206\t14.19395081\t14.1752257\t14.10086726\t14.16038301\t14.218206\t14.218206\t14.10086726\t14.25540728\t14.19395081\t14.09345014\t14.16038301\t14.218206\t14.25540728\t14.08087483\t14.16038301\t14.1752257\t14.14776746\t14.1752257\t14.19395081\t14.16038301\t14.25540728\t14.218206\t14.19395081\t14.25540728\t14.06270747\t14.10086726\t14.1752257\t14.218206\t14.11862071\t14.218206\t14.14776746\t14.13688086\t14.25540728\n", "\"ILMN_1343295\"\t11.42903686\t11.53817535\t11.51786395\t11.23076299\t10.84222976\t10.93051009\t10.84760207\t11.35624064\t11.05915557\t11.10188733\t11.17425541\t11.20592248\t10.98237716\t11.18461025\t11.32922647\t10.58287372\t10.68449119\t11.09362846\t10.8517102\t11.07847873\t11.29579305\t11.10350613\t10.71280893\t11.0557757\t11.18979944\t10.8581943\t11.28650678\t11.13280249\t11.41998638\t11.79814169\t11.12295909\t11.46113363\t10.50423267\t11.06204699\t10.93222505\t11.3510269\t11.47422508\t11.17613342\t11.04635523\t11.41562211\t11.08354752\t11.64162981\t10.75529044\t11.26923719\t11.08516101\t11.41562211\t11.2653319\t11.05118332\t11.33905258\t11.21987045\t11.38043761\t11.33411449\t10.91179221\t11.30971881\n", "\"ILMN_1651209\"\t6.987976286\t6.851134373\t6.861566691\t6.81213988\t6.917360192\t6.973243986\t7.055081298\t6.912652784\t6.896755555\t7.068544157\t6.960386218\t6.941237105\t7.004002801\t6.97885477\t6.849030552\t6.911183755\t6.971530563\t6.9508956\t6.888128419\t6.967897384\t6.837200319\t6.895563742\t7.025107248\t7.054401227\t6.906419861\t6.906712483\t6.947501407\t7.000813761\t6.937044118\t6.768386282\t6.86343792\t6.935974382\t6.953943579\t6.999739408\t6.983683901\t6.98394517\t7.080759025\t7.032938656\t6.984085156\t7.035836066\t7.06580392\t7.018064687\t7.150699317\t6.963386734\t7.029475205\t6.817425898\t6.870673232\t6.864789297\t6.967597884\t6.864123891\t6.881362231\t6.811224449\t6.915799034\t6.881624187\n", "\"ILMN_1651228\"\t13.15263073\t13.31297755\t13.31297755\t13.47107\t13.36279802\t13.09226537\t13.29960092\t13.01666008\t13.28597189\t13.10479801\t13.03091856\t12.87664575\t13.24725792\t13.34616023\t13.32994953\t13.05070779\t13.25174588\t13.05876844\t13.14329163\t13.17447307\t13.21754732\t13.24293262\t13.43234183\t13.17879882\t13.15263073\t13.19576297\t13.16573936\t13.16573936\t12.83570192\t12.88576196\t13.12666161\t13.02741117\t13.02397392\t12.88274037\t13.19576297\t13.16573936\t12.9517701\t13.00147873\t13.00493763\t13.02053775\t13.06314112\t12.92837742\t13.01246256\t12.9517701\t13.13513154\t13.18265557\t13.08031558\t12.97490896\t12.99811129\t13.06314112\t13.04291876\t13.15658421\t13.37143921\t13.02053775\n", "Total lines examined: 68\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 21236 rows\n", "First 20 gene IDs:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228',\n", " 'ILMN_1651229', 'ILMN_1651232', 'ILMN_1651237', 'ILMN_1651254',\n", " 'ILMN_1651259', 'ILMN_1651262', 'ILMN_1651278', 'ILMN_1651279',\n", " 'ILMN_1651296', 'ILMN_1651315', 'ILMN_1651316', 'ILMN_1651328',\n", " 'ILMN_1651336', 'ILMN_1651341', 'ILMN_1651343', 'ILMN_1651346'],\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", "# Add diagnostic code to check file content and structure\n", "print(\"Examining matrix file structure...\")\n", "with gzip.open(matrix_file, 'rt') as file:\n", " table_marker_found = False\n", " lines_read = 0\n", " for i, line in enumerate(file):\n", " lines_read += 1\n", " if '!series_matrix_table_begin' in line:\n", " table_marker_found = True\n", " print(f\"Found table marker at line {i}\")\n", " # Read a few lines after the marker to check data structure\n", " next_lines = [next(file, \"\").strip() for _ in range(5)]\n", " print(\"First few lines after marker:\")\n", " for next_line in next_lines:\n", " print(next_line)\n", " break\n", " if i < 10: # Print first few lines to see file structure\n", " print(f\"Line {i}: {line.strip()}\")\n", " if i > 100: # Don't read the entire file\n", " break\n", " \n", " if not table_marker_found:\n", " print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n", " print(f\"Total lines examined: {lines_read}\")\n", "\n", "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n", "try:\n", " print(\"\\nAttempting to extract 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: {str(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", "\n", "# If data extraction failed, try an alternative approach using pandas directly\n", "if not is_gene_available:\n", " print(\"\\nTrying alternative approach to read gene expression data...\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Skip lines until we find the marker\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Try to read the data directly with pandas\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", " \n", " if not gene_data.empty:\n", " print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", " else:\n", " print(\"Alternative extraction method also produced empty data\")\n", " except Exception as e:\n", " print(f\"Alternative extraction failed: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "8e3e0b08", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "e9a80940", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:27.308650Z", "iopub.status.busy": "2025-03-25T07:27:27.308531Z", "iopub.status.idle": "2025-03-25T07:27:27.310480Z", "shell.execute_reply": "2025-03-25T07:27:27.310200Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers visible in the data, I can analyze the format\n", "# The IDs starting with \"ILMN_\" are Illumina BeadArray probe identifiers\n", "# These are not standard human gene symbols but rather probe identifiers specific to Illumina microarrays\n", "# They need to be mapped to human gene symbols for biological interpretation\n", "\n", "# To make this observation explicit for the preprocessing pipeline:\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "f3dfbe76", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "ffa41484", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:27.311678Z", "iopub.status.busy": "2025-03-25T07:27:27.311578Z", "iopub.status.idle": "2025-03-25T07:27:30.191046Z", "shell.execute_reply": "2025-03-25T07:27:30.190655Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 1194905 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 47323 out of 1194905\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "40742252", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "f2639fad", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:30.192504Z", "iopub.status.busy": "2025-03-25T07:27:30.192381Z", "iopub.status.idle": "2025-03-25T07:27:30.731372Z", "shell.execute_reply": "2025-03-25T07:27:30.730993Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping dataframe...\n", "Created gene mapping with 44837 rows\n", "First few rows of gene mapping:\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "Number of unique probe IDs in mapping: 44837\n", "Number of unique gene symbols in mapping: 31432\n", "\n", "Converting probe-level measurements to gene expression data...\n", "Generated gene expression data with 12663 rows (genes)\n", "First few rows of gene expression data:\n", " GSM3034383 GSM3034384 GSM3034385 GSM3034386 GSM3034387 \\\n", "Gene \n", "A1BG 6.873444 6.955637 6.948351 6.942078 6.914520 \n", "A2LD1 7.258187 7.171830 7.046285 6.971499 7.179190 \n", "A4GALT 6.599934 6.718233 6.633495 6.602242 6.518970 \n", "A4GNT 7.005378 6.861352 7.097835 6.759387 6.939359 \n", "AAAS 7.174038 7.156466 7.108116 6.955536 7.108179 \n", "\n", " GSM3034388 GSM3034389 GSM3034390 GSM3034391 GSM3034392 ... \\\n", "Gene ... \n", "A1BG 7.149979 6.962675 6.981696 7.020364 6.974812 ... \n", "A2LD1 7.303954 7.088017 7.251346 7.229036 7.101749 ... \n", "A4GALT 6.527654 6.543837 6.648973 6.534444 6.574655 ... \n", "A4GNT 6.818557 7.012914 6.906397 6.979199 7.063826 ... \n", "AAAS 7.046239 7.159800 7.190198 7.191360 7.041803 ... \n", "\n", " GSM3034427 GSM3034428 GSM3034429 GSM3034430 GSM3034431 \\\n", "Gene \n", "A1BG 6.974252 6.937765 7.169147 7.003868 6.892058 \n", "A2LD1 7.344385 7.278327 7.052729 7.265036 7.193490 \n", "A4GALT 6.668269 6.676636 6.661740 6.655936 6.622571 \n", "A4GNT 6.909004 6.872916 6.916880 6.933814 6.768268 \n", "AAAS 7.005530 7.032234 7.112380 7.089919 7.073288 \n", "\n", " GSM3034432 GSM3034433 GSM3034434 GSM3034435 GSM3034436 \n", "Gene \n", "A1BG 6.886202 7.031371 7.021414 6.907370 6.882733 \n", "A2LD1 7.156488 7.282306 7.343757 7.210973 7.822609 \n", "A4GALT 6.633992 6.562606 6.619644 6.647229 6.575994 \n", "A4GNT 7.003868 6.980024 6.953557 6.898276 6.955680 \n", "AAAS 7.079792 7.200300 6.973536 7.193659 7.136043 \n", "\n", "[5 rows x 54 columns]\n", "\n", "Sample of gene symbols in the processed data:\n", "['A1BG', 'A2LD1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AACSL', 'AADACL1', 'AADAT', 'AAGAB']\n", "\n", "Saving gene expression data to ../../output/preprocess/LDL_Cholesterol_Levels/gene_data/GSE111567.csv...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved successfully with 12663 genes and 54 samples\n" ] } ], "source": [ "# 1. Determine which columns in gene_annotation store identifiers and gene symbols\n", "# From the previous step, we can see:\n", "# - 'ID' column in gene_annotation stores the probe identifiers (ILMN_*)\n", "# - 'Symbol' column contains gene symbols\n", "\n", "# 2. Get the gene mapping dataframe by extracting these two columns\n", "print(\"Creating gene mapping dataframe...\")\n", "try:\n", " # Extract the relevant columns for mapping\n", " probe_col = 'ID'\n", " gene_col = 'Symbol'\n", " \n", " # Create the mapping dataframe\n", " mapping_df = get_gene_mapping(gene_annotation, probe_col, gene_col)\n", " print(f\"Created gene mapping with {len(mapping_df)} rows\")\n", " print(\"First few rows of gene mapping:\")\n", " print(mapping_df.head())\n", " \n", " # Check how many unique probe IDs are in the mapping\n", " unique_probes = mapping_df['ID'].nunique()\n", " print(f\"Number of unique probe IDs in mapping: {unique_probes}\")\n", " \n", " # Check how many unique gene symbols are in the mapping\n", " gene_symbols = []\n", " for gene_list in mapping_df['Gene']:\n", " if isinstance(gene_list, list):\n", " gene_symbols.extend(gene_list)\n", " else:\n", " gene_symbols.append(gene_list)\n", " unique_genes = len(set(gene_symbols))\n", " print(f\"Number of unique gene symbols in mapping: {unique_genes}\")\n", " \n", " # 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", " print(\"\\nConverting probe-level measurements to gene expression data...\")\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " print(f\"Generated gene expression data with {len(gene_data)} rows (genes)\")\n", " print(\"First few rows of gene expression data:\")\n", " print(gene_data.head())\n", " \n", " # Verify we have real gene symbols in the index\n", " print(\"\\nSample of gene symbols in the processed data:\")\n", " print(gene_data.index[:10].tolist())\n", " \n", "except Exception as e:\n", " print(f\"Error in gene mapping: {e}\")\n", " is_gene_available = False\n", "\n", "# Save the processed gene data if available\n", "if is_gene_available and not gene_data.empty:\n", " print(f\"\\nSaving gene expression data to {out_gene_data_file}...\")\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 successfully with {len(gene_data)} genes and {gene_data.shape[1]} samples\")\n", "else:\n", " print(\"Gene expression data not available or empty - not saving\")\n" ] }, { "cell_type": "markdown", "id": "3fb15e12", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "85ba50b7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:30.732802Z", "iopub.status.busy": "2025-03-25T07:27:30.732684Z", "iopub.status.idle": "2025-03-25T07:27:31.219599Z", "shell.execute_reply": "2025-03-25T07:27:31.219177Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Saving normalized gene data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/LDL_Cholesterol_Levels/gene_data/GSE111567.csv\n", "\n", "Extracting clinical data...\n", "Clinical data saved to ../../output/preprocess/LDL_Cholesterol_Levels/clinical_data/GSE111567.csv\n", "Clinical data shape: (3, 54)\n", "Trait information available: False\n", "\n", "Linking clinical and genetic data...\n", "Cannot link data: clinical data is not available\n", "\n", "Skipping missing value handling and bias evaluation as linked data is not available\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE111567. Preprocessing failed.\n", "\n", "Dataset usability for LDL_Cholesterol_Levels association studies: False\n", "Reason: Dataset does not contain required trait information\n" ] } ], "source": [ "# 1. Save the normalized gene expression data from the previous step\n", "print(\"\\nSaving normalized gene 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\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Extract clinical data from the matrix file\n", "print(\"\\nExtracting clinical data...\")\n", "try:\n", " # Get the file paths again to make sure we have them\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Extract background information and clinical data\n", " background_info, clinical_data = get_background_and_clinical_data(\n", " matrix_file, \n", " prefixes_a=['!Series_title', '!Series_summary', '!Series_overall_design'],\n", " prefixes_b=['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", " )\n", " \n", " # Process clinical data using trait information from Step 2\n", " trait_row = 1 # Based on analysis in step 2 - group (OW/OB vs NW/MONW)\n", " gender_row = 0 # Gender data\n", " age_row = 2 # Age data\n", " \n", " # Define conversion functions based on Step 2\n", " def convert_trait(value):\n", " \"\"\"Convert trait value (binary: 1 for OW/OB, 0 for NW/MONW)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'OW/OB' in value:\n", " return 1 # Overweight/Obese is associated with higher LDL cholesterol\n", " elif 'NW' in value or 'MONW' in value:\n", " return 0 # Normal weight (includes metabolically obese normal weight)\n", " else:\n", " return None\n", "\n", " def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0: female, 1: male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert gender\n", " if value.lower() == 'woman':\n", " return 0\n", " elif value.lower() == 'man':\n", " return 1\n", " else:\n", " return None\n", " \n", " def convert_age(value):\n", " \"\"\"Convert age value to float\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value) # Convert to float for continuous variable\n", " except:\n", " return None\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " \n", " # Check if we have valid trait information\n", " is_trait_available = trait_row is not None and not selected_clinical_df.loc[trait].isnull().all()\n", " print(f\"Trait information available: {is_trait_available}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", " selected_clinical_df = pd.DataFrame()\n", "\n", "# 3. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if is_trait_available and not selected_clinical_df.empty:\n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n", " print(f\"Created linked data with {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " else:\n", " print(\"Cannot link data: clinical data is not available\")\n", " linked_data = pd.DataFrame()\n", " is_trait_available = False\n", "except Exception as e:\n", " print(f\"Error linking clinical and genetic data: {e}\")\n", " is_trait_available = False\n", " linked_data = pd.DataFrame()\n", "\n", "# 4. Handle missing values in the linked data\n", "if is_trait_available and not linked_data.empty:\n", " print(\"\\nHandling missing values...\")\n", " try:\n", " # Rename the first column to the trait name for consistency\n", " if linked_data.columns[0] != trait:\n", " linked_data = linked_data.rename(columns={linked_data.columns[0]: trait})\n", " \n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values: {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " \n", " # 5. Determine whether the trait and demographic features are biased\n", " print(\"\\nEvaluating feature bias...\")\n", " try:\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Trait bias determination: {is_biased}\")\n", " print(f\"Final linked data shape: {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " except Exception as e:\n", " print(f\"Error evaluating feature bias: {e}\")\n", " is_biased = True\n", "else:\n", " print(\"\\nSkipping missing value handling and bias evaluation as linked data is not available\")\n", " is_biased = True\n", "\n", "# 6. Validate and save cohort information\n", "print(\"\\nPerforming final validation...\")\n", "note = \"\"\n", "if not is_trait_available:\n", " note = \"Dataset does not contain required trait information\"\n", "elif is_biased:\n", " note = \"Dataset has severe bias in the trait distribution\"\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=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", "# 7. Save the linked data if usable\n", "print(f\"\\nDataset usability for {trait} association studies: {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\"Final linked data saved to {out_data_file}\")\n", "else:\n", " if note:\n", " print(f\"Reason: {note}\")\n", " else:\n", " print(\"Dataset does not meet quality criteria for the specified trait\")" ] } ], "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 }