{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "52d26d79", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:38:50.744501Z", "iopub.status.busy": "2025-03-25T05:38:50.744397Z", "iopub.status.idle": "2025-03-25T05:38:50.932901Z", "shell.execute_reply": "2025-03-25T05:38:50.932527Z" } }, "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 = \"Heart_rate\"\n", "cohort = \"GSE236927\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Heart_rate\"\n", "in_cohort_dir = \"../../input/GEO/Heart_rate/GSE236927\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Heart_rate/GSE236927.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Heart_rate/gene_data/GSE236927.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Heart_rate/clinical_data/GSE236927.csv\"\n", "json_path = \"../../output/preprocess/Heart_rate/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3cf2f73e", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a86c01d5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:38:50.934463Z", "iopub.status.busy": "2025-03-25T05:38:50.934306Z", "iopub.status.idle": "2025-03-25T05:38:51.028894Z", "shell.execute_reply": "2025-03-25T05:38:51.028535Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Inflammatory markers and frailty in home-dwelling elderly, a cross-sectional study\"\n", "!Series_summary\t\"Low-grade, chronic inflammation during ageing (“inflammageing”) is suggested to be involved in the development of frailty in older age. However, studies on the association between frailty, using the frailty index definition, and inflammatory markers are limited.\"\n", "!Series_summary\t\"The aim of this study was to investigate the relationship between inflammatory markers and frailty index (FI) in older, home-dwelling adults. Home-dwelling men and women aged ≥ 70 years old, living in South-East Norway were recruited and included in a cross-sectional study. The FI used in the current study was developed according to Rockwood’s frailty index and included 38 variables, resulting in an FI score between 0 and 1 for each participant. Circulating inflammatory markers (IL-6, CRP, IGF-1, cystatin C, cathepsin S, and glycoprotein Acetyls) were analyzed from non-fasting blood samples using ELISA. Whole-genome PBMC transcriptomics was used to study the association between FI score and inflammation.\"\n", "!Series_summary\t\"The present study was a cross-sectional study that included home-dwelling men and women aged ≥ 70 years old, living in the Skedsmo area, South-East Norway. The study was conducted in 2014/2015 and has been described previously [Ottestad I, Ulven SM, Øyri LKL, Sandvei KS, Gjevestad GO, Bye A, et al. Reduced plasma concentration of branched-chain amino acids in sarcopenic older subjects: a cross-sectional study. Br J Nutr. 2018;120(4):445-53]. The participants were recruited by the National Register and received an invitation letter by mail. Briefly, a total of 2820 subjects were invited, and 437 subjects participated in the study. The participants met for a single study visit, and data was collected on dietary intake, body weight and composition, physical performance, medical history, cognitive function, risk of malnutrition, anthropometric measurements, blood pressure, heart rate, and quality of life. Non-fasting blood samples were also collected.\"\n", "!Series_overall_design\t\"Gene expression data from PBMCs isolated from non-fasting blood samples collected at a screening visit (Amarone cross-sectional) for a randomized trial (Amarone RCT):\"\n", "!Series_overall_design\t\"Data at cross-sectional screening visit: n = 437\"\n", "!Series_overall_design\t\"PBMC samples analyzed with microarray (females only): n = 96\"\n", "!Series_overall_design\t\"PBMC samples analyzed with microarray (females only), excl. outliers: n = 95 (excl. sample 52 - only non-normalized data provided)\"\n", "!Series_overall_design\t\"PBMC samples with available outcome data (i.e., the FI score): n = 88 (excl. samples 2, 8, 14, 15, 18, 21, and 28)\"\n", "Sample Characteristics Dictionary:\n", "{0: ['sex (female/male): Female', 'fi score (range 0-1): 0.223684210526316', 'fi score (range 0-1): 0.25', 'fi score (range 0-1): 0.138157894736842', 'fi score (range 0-1): 0.375', 'fi score (range 0-1): 0.0855263157894737', 'fi score (range 0-1): 0.125', 'fi score (range 0-1): 0.111842105263158', 'fi score (range 0-1): 0.0921052631578947', 'fi score (range 0-1): 0.0986842105263158', 'fi score (range 0-1): 0.151315789473684', 'fi score (range 0-1): 0.236842105263158', 'fi score (range 0-1): 0.304054054054054', 'fi score (range 0-1): 0.309210526315789', 'fi score (range 0-1): 0.269736842105263', 'fi score (range 0-1): 0.184210526315789', 'fi score (range 0-1): 0.190789473684211', 'fi score (range 0-1): 0.355263157894737', 'fi score (range 0-1): 0.467105263157895', 'fi score (range 0-1): 0.434210526315789', 'fi score (range 0-1): 0.0657894736842105', 'fi score (range 0-1): 0.131578947368421', 'fi score (range 0-1): 0.164473684210526', 'fi score (range 0-1): 0.105263157894737', 'fi score (range 0-1): 0.144736842105263', 'fi score (range 0-1): 0.157894736842105', 'fi score (range 0-1): 0.282894736842105', 'fi score (range 0-1): 0.171052631578947', 'fi score (range 0-1): 0.118421052631579', 'fi score (range 0-1): 0.328947368421053'], 1: ['age (y): 79', 'age (y): 92', 'age (y): 75', 'age (y): 88', 'age (y): 74', 'age (y): 82', 'age (y): 71', 'sex (female/male): Female'], 2: ['bmi (kg(m2): 36.2', 'bmi (kg(m2): 23', 'bmi (kg(m2): 36.6', 'bmi (kg(m2): 22.8', 'bmi (kg(m2): 30', 'bmi (kg(m2): 25.5', 'bmi (kg(m2): 19', 'age (y): 88', 'age (y): 82', 'age (y): 83', 'age (y): 87', 'age (y): 76', 'age (y): 77', 'age (y): 73', 'age (y): 85', 'age (y): 91', 'age (y): 74', 'age (y): 79', 'age (y): 80', 'age (y): 75', 'age (y): 81', 'age (y): 90', 'age (y): 70', 'age (y): 71', 'age (y): 84', 'age (y): 86', 'age (y): 78', 'age (y): 72'], 3: ['monocytes (absolute values x109/l): 0.5', 'monocytes (absolute values x109/l): 0.7', 'monocytes (absolute values x109/l): 0.4', 'monocytes (absolute values x109/l): 0.6', 'monocytes (absolute values x109/l): 0.3', 'bmi (kg(m2): 23.2', 'bmi (kg(m2): 27', 'bmi (kg(m2): 26.1', 'bmi (kg(m2): 29.6', 'bmi (kg(m2): 24', 'bmi (kg(m2): 22.8', 'bmi (kg(m2): 27.5', 'bmi (kg(m2): 23.1', 'bmi (kg(m2): 26.5', 'bmi (kg(m2): 24.3', 'bmi (kg(m2): 24.8', 'bmi (kg(m2): 30.3', 'bmi (kg(m2): 28.8', 'bmi (kg(m2): 23.5', 'bmi (kg(m2): 18.3', 'bmi (kg(m2): 31.8', 'bmi (kg(m2): 28.9', 'bmi (kg(m2): 34.3', 'bmi (kg(m2): 20.7', 'bmi (kg(m2): 22.1', 'bmi (kg(m2): 23.8', 'bmi (kg(m2): 30.4', 'bmi (kg(m2): 25.8', 'bmi (kg(m2): 25.1', 'bmi (kg(m2): 22.5'], 4: ['lymphocytes (absolute values x109/l): 1', 'lymphocytes (absolute values x109/l): 6.6', 'lymphocytes (absolute values x109/l): 1.8', 'lymphocytes (absolute values x109/l): 1.7', 'lymphocytes (absolute values x109/l): 1.1', 'lymphocytes (absolute values x109/l): 1.9', 'monocytes (absolute values x109/l): 0.5', 'monocytes (absolute values x109/l): 0.3', 'monocytes (absolute values x109/l): 0.4', 'monocytes (absolute values x109/l): 0.7', 'monocytes (absolute values x109/l): 0.6', 'monocytes (absolute values x109/l): 1.1', 'monocytes (absolute values x109/l): 0.2', 'monocytes (absolute values x109/l): 0.9', 'monocytes (absolute values x109/l): 1'], 5: [nan, 'lymphocytes (absolute values x109/l): 1.8', 'lymphocytes (absolute values x109/l): 2.2', 'lymphocytes (absolute values x109/l): 2.1', 'lymphocytes (absolute values x109/l): 1.3', 'lymphocytes (absolute values x109/l): 1.7', 'lymphocytes (absolute values x109/l): 1.2', 'lymphocytes (absolute values x109/l): 3.2', 'lymphocytes (absolute values x109/l): 1.9', 'lymphocytes (absolute values x109/l): 1.1', 'lymphocytes (absolute values x109/l): 1', 'lymphocytes (absolute values x109/l): 1.5', 'lymphocytes (absolute values x109/l): 2', 'lymphocytes (absolute values x109/l): 2.7', 'lymphocytes (absolute values x109/l): 1.6', 'lymphocytes (absolute values x109/l): 1.4', 'lymphocytes (absolute values x109/l): 2.8', 'lymphocytes (absolute values x109/l): 2.5', 'lymphocytes (absolute values x109/l): 3', 'lymphocytes (absolute values x109/l): 2.6', 'lymphocytes (absolute values x109/l): 2.4', 'lymphocytes (absolute values x109/l): 2.3', 'lymphocytes (absolute values x109/l): 0.5']}\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": "30396a05", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "23ffbf4e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:38:51.030194Z", "iopub.status.busy": "2025-03-25T05:38:51.030073Z", "iopub.status.idle": "2025-03-25T05:38:51.036634Z", "shell.execute_reply": "2025-03-25T05:38:51.036326Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information - \"Whole-genome PBMC transcriptomics\" is mentioned,\n", "# which indicates gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Identify the keys in sample characteristics\n", "\n", "# Heart rate data: Not explicitly mentioned, but background mentions it was collected\n", "# Looking at the sample characteristics dictionary, we don't see heart rate data\n", "trait_row = None # No heart rate data available\n", "\n", "# Age data: Available in row 1 and 2, but more complete in row 2\n", "age_row = 2\n", "\n", "# Gender data: Only females were included in the microarray analysis\n", "gender_row = 0 # Row 0 has sex data but all are female\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " # Not used since trait_row is None, but defined for completeness\n", " if value is None:\n", " return None\n", " try:\n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_age(value):\n", " # Age is continuous\n", " if value is None:\n", " return None\n", " try:\n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " # Gender is binary, but only females in this dataset\n", " if value is None:\n", " return None\n", " try:\n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " if value == 'female':\n", " return 0\n", " elif value == 'male':\n", " return 1\n", " else:\n", " return None\n", " except:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Perform initial filtering on usability\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(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", "# 4. Clinical Feature Extraction\n", "# This should be skipped because trait_row is None (heart rate data not available)\n" ] }, { "cell_type": "markdown", "id": "b0f7f9ed", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "90ceb2b5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:38:51.037757Z", "iopub.status.busy": "2025-03-25T05:38:51.037647Z", "iopub.status.idle": "2025-03-25T05:38:51.187981Z", "shell.execute_reply": "2025-03-25T05:38:51.187626Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 75\n", "Header line: \"ID_REF\"\t\"GSM7585856\"\t\"GSM7585857\"\t\"GSM7585858\"\t\"GSM7585859\"\t\"GSM7585860\"\t\"GSM7585861\"\t\"GSM7585862\"\t\"GSM7585863\"\t\"GSM7585864\"\t\"GSM7585865\"\t\"GSM7585866\"\t\"GSM7585867\"\t\"GSM7585868\"\t\"GSM7585869\"\t\"GSM7585870\"\t\"GSM7585871\"\t\"GSM7585872\"\t\"GSM7585873\"\t\"GSM7585874\"\t\"GSM7585875\"\t\"GSM7585876\"\t\"GSM7585877\"\t\"GSM7585878\"\t\"GSM7585879\"\t\"GSM7585880\"\t\"GSM7585881\"\t\"GSM7585882\"\t\"GSM7585883\"\t\"GSM7585884\"\t\"GSM7585885\"\t\"GSM7585886\"\t\"GSM7585887\"\t\"GSM7585888\"\t\"GSM7585889\"\t\"GSM7585890\"\t\"GSM7585891\"\t\"GSM7585892\"\t\"GSM7585893\"\t\"GSM7585894\"\t\"GSM7585895\"\t\"GSM7585896\"\t\"GSM7585897\"\t\"GSM7585898\"\t\"GSM7585899\"\t\"GSM7585900\"\t\"GSM7585901\"\t\"GSM7585902\"\t\"GSM7585903\"\t\"GSM7585904\"\t\"GSM7585905\"\t\"GSM7585906\"\t\"GSM7585907\"\t\"GSM7585908\"\t\"GSM7585909\"\t\"GSM7585910\"\t\"GSM7585911\"\t\"GSM7585912\"\t\"GSM7585913\"\t\"GSM7585914\"\t\"GSM7585915\"\t\"GSM7585916\"\t\"GSM7585917\"\t\"GSM7585918\"\t\"GSM7585919\"\t\"GSM7585920\"\t\"GSM7585921\"\t\"GSM7585922\"\t\"GSM7585923\"\t\"GSM7585924\"\t\"GSM7585925\"\t\"GSM7585926\"\t\"GSM7585927\"\t\"GSM7585928\"\t\"GSM7585929\"\t\"GSM7585930\"\t\"GSM7585931\"\t\"GSM7585932\"\t\"GSM7585933\"\t\"GSM7585934\"\t\"GSM7585935\"\t\"GSM7585936\"\t\"GSM7585937\"\t\"GSM7585938\"\t\"GSM7585939\"\t\"GSM7585940\"\t\"GSM7585941\"\t\"GSM7585942\"\t\"GSM7585943\"\t\"GSM7585944\"\t\"GSM7585945\"\t\"GSM7585946\"\t\"GSM7585947\"\t\"GSM7585948\"\t\"GSM7585949\"\t\"GSM7585950\"\n", "First data line: \"ILMN_1651228\"\t12.32295124\t12.55255262\t12.5967424\t12.41494499\t12.27370061\t12.37238164\t12.39253628\t12.37213272\t12.5331569\t12.44968431\t12.43003266\t12.47409277\t12.59401838\t12.29813819\t12.63490182\t12.45316752\t12.25754853\t12.22841234\t12.48713958\t12.62586115\t12.64600221\t12.75542302\t12.49734329\t12.3524277\t12.4552082\t12.35128866\t12.46099716\t12.17498486\t12.317933\t12.29509405\t12.11017654\t12.5652803\t12.31781632\t12.64014869\t12.74254842\t12.47515341\t12.41751446\t12.55644572\t12.63490182\t12.62779791\t12.39167822\t12.47084166\t12.45556025\t12.51391564\t12.7127631\t12.53229931\t12.67071799\t12.34145231\t12.47662061\t12.46849986\t12.35287231\t12.02868393\t12.2408106\t12.11680013\t12.13118975\t12.35248286\t12.23259049\t12.12956779\t12.45556025\t12.48125116\t12.68735824\t12.42363679\t12.50325242\t12.37480064\t12.02114362\t12.41381025\t12.50927757\t12.51152942\t12.4055523\t12.22360048\t12.49858361\t12.25302691\t12.36445255\t12.36562335\t12.36980419\t12.27725754\t12.2408106\t12.45339766\t12.4506598\t12.59969989\t12.52570932\t12.43651507\t12.25280266\t12.53974453\t12.56347132\t12.53229931\t12.56933127\t12.37027198\t12.50753175\t12.44673684\t12.53754187\t12.22702394\t12.57779748\t12.53491688\t12.39511115\n", "Index(['ILMN_1651228', 'ILMN_1651229', 'ILMN_1651254', 'ILMN_1651262',\n", " 'ILMN_1651278', 'ILMN_1651296', 'ILMN_1651315', 'ILMN_1651336',\n", " 'ILMN_1651341', 'ILMN_1651343', 'ILMN_1651347', 'ILMN_1651364',\n", " 'ILMN_1651378', 'ILMN_1651385', 'ILMN_1651403', 'ILMN_1651405',\n", " 'ILMN_1651429', 'ILMN_1651433', 'ILMN_1651438', 'ILMN_1651496'],\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": "af343089", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "9e764e24", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:38:51.189562Z", "iopub.status.busy": "2025-03-25T05:38:51.189429Z", "iopub.status.idle": "2025-03-25T05:38:51.191671Z", "shell.execute_reply": "2025-03-25T05:38:51.191384Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the expression data\n", "# The identifiers start with \"ILMN_\" followed by numbers, which indicates they are Illumina probe IDs\n", "# These are not standard human gene symbols, but rather probe identifiers from Illumina microarray platforms\n", "# They will need to be mapped to human gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "d663253f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "8028b6b0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:38:51.192716Z", "iopub.status.busy": "2025-03-25T05:38:51.192599Z", "iopub.status.idle": "2025-03-25T05:38:52.116245Z", "shell.execute_reply": "2025-03-25T05:38:52.115633Z" } }, "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 = GSE236927\n", "Line 6: !Series_title = Inflammatory markers and frailty in home-dwelling elderly, a cross-sectional study\n", "Line 7: !Series_geo_accession = GSE236927\n", "Line 8: !Series_status = Public on Sep 01 2023\n", "Line 9: !Series_submission_date = Jul 10 2023\n", "Line 10: !Series_last_update_date = Mar 06 2024\n", "Line 11: !Series_pubmed_id = 38373890\n", "Line 12: !Series_summary = Low-grade, chronic inflammation during ageing (“inflammageing”) is suggested to be involved in the development of frailty in older age. However, studies on the association between frailty, using the frailty index definition, and inflammatory markers are limited.\n", "Line 13: !Series_summary = The aim of this study was to investigate the relationship between inflammatory markers and frailty index (FI) in older, home-dwelling adults. Home-dwelling men and women aged ≥ 70 years old, living in South-East Norway were recruited and included in a cross-sectional study. The FI used in the current study was developed according to Rockwood’s frailty index and included 38 variables, resulting in an FI score between 0 and 1 for each participant. Circulating inflammatory markers (IL-6, CRP, IGF-1, cystatin C, cathepsin S, and glycoprotein Acetyls) were analyzed from non-fasting blood samples using ELISA. Whole-genome PBMC transcriptomics was used to study the association between FI score and inflammation.\n", "Line 14: !Series_summary = The present study was a cross-sectional study that included home-dwelling men and women aged ≥ 70 years old, living in the Skedsmo area, South-East Norway. The study was conducted in 2014/2015 and has been described previously [Ottestad I, Ulven SM, Øyri LKL, Sandvei KS, Gjevestad GO, Bye A, et al. Reduced plasma concentration of branched-chain amino acids in sarcopenic older subjects: a cross-sectional study. Br J Nutr. 2018;120(4):445-53]. The participants were recruited by the National Register and received an invitation letter by mail. Briefly, a total of 2820 subjects were invited, and 437 subjects participated in the study. The participants met for a single study visit, and data was collected on dietary intake, body weight and composition, physical performance, medical history, cognitive function, risk of malnutrition, anthropometric measurements, blood pressure, heart rate, and quality of life. Non-fasting blood samples were also collected.\n", "Line 15: !Series_overall_design = Gene expression data from PBMCs isolated from non-fasting blood samples collected at a screening visit (Amarone cross-sectional) for a randomized trial (Amarone RCT):\n", "Line 16: !Series_overall_design = Data at cross-sectional screening visit: n = 437\n", "Line 17: !Series_overall_design = PBMC samples analyzed with microarray (females only): n = 96\n", "Line 18: !Series_overall_design = PBMC samples analyzed with microarray (females only), excl. outliers: n = 95 (excl. sample 52 - only non-normalized data provided)\n", "Line 19: !Series_overall_design = PBMC samples with available outcome data (i.e., the FI score): n = 88 (excl. samples 2, 8, 14, 15, 18, 21, and 28)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\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, 6510136, 7560739, 1450438, 1240647], '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" ] } ], "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": "e865fb7d", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "180e2775", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:38:52.118144Z", "iopub.status.busy": "2025-03-25T05:38:52.117973Z", "iopub.status.idle": "2025-03-25T05:38:52.771527Z", "shell.execute_reply": "2025-03-25T05:38:52.770946Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (44837, 2)\n", "First few rows of mapping dataframe:\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", "Converted gene expression data shape: (10529, 95)\n", "First few rows of gene expression data:\n", " GSM7585856 GSM7585857 GSM7585858 GSM7585859 GSM7585860 \\\n", "Gene \n", "A2LD1 6.216161 6.036463 6.231927 5.912848 5.875233 \n", "AAAS 5.317495 5.359953 5.309062 5.433926 5.665110 \n", "AACS 4.781565 4.918706 4.809868 4.708769 4.773897 \n", "AACSL 4.776817 4.737485 4.731567 4.979210 4.654471 \n", "AADACL1 6.759696 6.868990 6.817230 6.650515 6.922026 \n", "\n", " GSM7585861 GSM7585862 GSM7585863 GSM7585864 GSM7585865 ... \\\n", "Gene ... \n", "A2LD1 5.582682 6.314095 6.180358 7.093845 6.070710 ... \n", "AAAS 5.352067 5.536034 5.636618 5.467182 5.382488 ... \n", "AACS 4.906523 5.164057 5.046632 5.057237 4.654866 ... \n", "AACSL 4.784909 4.545740 4.640646 4.656238 5.001632 ... \n", "AADACL1 6.651647 6.728300 6.731082 6.889685 6.460625 ... \n", "\n", " GSM7585941 GSM7585942 GSM7585943 GSM7585944 GSM7585945 \\\n", "Gene \n", "A2LD1 6.624461 6.784055 6.508370 6.175362 6.235865 \n", "AAAS 5.059327 5.259458 5.279881 5.414875 5.447947 \n", "AACS 5.083707 4.895253 4.968723 4.896536 5.000050 \n", "AACSL 4.944150 4.541426 4.685974 5.016430 4.763695 \n", "AADACL1 7.086103 7.002856 7.062380 6.911614 6.821952 \n", "\n", " GSM7585946 GSM7585947 GSM7585948 GSM7585949 GSM7585950 \n", "Gene \n", "A2LD1 6.922990 5.954697 6.160867 6.358471 6.265328 \n", "AAAS 5.121143 5.306561 5.556125 5.164788 5.382456 \n", "AACS 4.608832 5.002904 5.264610 5.074118 4.907106 \n", "AACSL 4.694700 4.984881 4.979320 4.907269 4.539084 \n", "AADACL1 6.999460 7.349917 7.449462 6.919455 7.128813 \n", "\n", "[5 rows x 95 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Heart_rate/gene_data/GSE236927.csv\n" ] } ], "source": [ "# 1. Identify the columns containing probe IDs and gene symbols in the gene annotation data\n", "# From the preview, we can see:\n", "# - The \"ID\" column corresponds to Illumina probe IDs (starts with ILMN_)\n", "# - The \"Symbol\" column contains gene symbols\n", "\n", "# 2. Extract mapping information from gene annotation\n", "mapping_df = gene_annotation[['ID', 'Symbol']].copy()\n", "mapping_df = mapping_df.dropna(subset=['Symbol']) # Drop rows without gene symbols\n", "mapping_df = mapping_df.astype({'ID': 'str'}) # Ensure ID is string type\n", "# Rename Symbol column to Gene as expected by apply_gene_mapping function\n", "mapping_df = mapping_df.rename(columns={'Symbol': 'Gene'})\n", "\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"First few rows of mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Converted gene expression data shape: {gene_data.shape}\")\n", "print(\"First few rows of gene expression data:\")\n", "print(gene_data.head())\n", "\n", "# Save the gene expression data to 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 to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "55dae3fd", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "fb3bd91c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:38:52.773193Z", "iopub.status.busy": "2025-03-25T05:38:52.773068Z", "iopub.status.idle": "2025-03-25T05:38:57.853257Z", "shell.execute_reply": "2025-03-25T05:38:57.852714Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data saved to ../../output/preprocess/Heart_rate/clinical_data/GSE236927.csv\n", "Gene data shape: (10529, 95)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/Heart_rate/gene_data/GSE236927.csv\n", "Linked data shape: (95, 10531)\n", "Linked data columns preview: ['Heart_rate', 'Gender', 'A2LD1', 'AAAS', 'AACS', 'AACSL', 'AADACL1', 'AAGAB', 'AAK1', 'AAMP']\n", "\n", "Missing values before handling:\n", " Trait (Heart_rate) missing: 0 out of 95\n", " Genes with >20% missing: 0 out of 10529\n", " Samples with >5% missing genes: 0 out of 95\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (95, 10531)\n", "Quartiles for 'Heart_rate':\n", " 25%: 73.0\n", " 50% (Median): 76.0\n", " 75%: 81.5\n", "Min: 19.0\n", "Max: 91.0\n", "The distribution of the feature 'Heart_rate' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 95 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Heart_rate/GSE236927.csv\n" ] } ], "source": [ "# 1. Load the clinical data again to ensure we have the correct data\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Get a proper view of the sample characteristics\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# Extract heart rate data using the convert_trait function from Step 2\n", "def convert_trait(value):\n", " \"\"\"Convert heart rate value to continuous numeric type.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " try:\n", " # Extract the numerical value after the colon and \"bpm:\"\n", " parts = value.split(\":\")\n", " if len(parts) < 2:\n", " return None\n", " numeric_value = parts[1].strip()\n", " # Remove possible 'bpm' text and convert to float\n", " numeric_value = numeric_value.replace(\"bpm\", \"\").strip()\n", " return float(numeric_value)\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "# Gender conversion function (defined in Step 2)\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0=female, 1=male).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " try:\n", " gender = value.split(\":\")[1].strip().lower()\n", " if \"male\" in gender:\n", " return 1\n", " elif \"female\" in gender:\n", " return 0\n", " else:\n", " return None\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "# Extract clinical features based on the rows identified in Step 2\n", "trait_row = 2 # Heart rate data is in row 2\n", "gender_row = 0 # Gender data is in row 0\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", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", ")\n", "\n", "# Transpose the clinical data for easier processing\n", "selected_clinical_df = selected_clinical_df.T\n", "selected_clinical_df.index.name = 'Sample'\n", "\n", "# Save clinical data to file\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", "\n", "# 2. Keep using the original gene expression data since mapping failed\n", "# The gene_data object from Step 6 already contains our gene expression data\n", "print(f\"Gene data shape: {gene_data.shape}\")\n", "\n", "# Save the gene data to the output 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 data saved to {out_gene_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "# Make sure sample IDs match between clinical and genetic data\n", "common_samples = list(set(selected_clinical_df.index) & set(gene_data.columns))\n", "if not common_samples:\n", " print(\"Warning: No matching sample IDs between clinical and genetic data!\")\n", " # Try to match based on order rather than IDs if needed\n", " selected_clinical_df.index = gene_data.columns[:len(selected_clinical_df)]\n", " common_samples = list(selected_clinical_df.index)\n", "\n", "# Select only common samples from both datasets\n", "clinical_subset = selected_clinical_df.loc[common_samples]\n", "gene_subset = gene_data[common_samples]\n", "\n", "# Now link the data\n", "linked_data = pd.concat([clinical_subset, gene_subset.T], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(f\"Linked data columns preview: {list(linked_data.columns[:10])}\")\n", "\n", "# 4. Handle missing values\n", "print(\"\\nMissing values before handling:\")\n", "print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", "gene_cols = [col for col in linked_data.columns if col != trait and col != 'Gender']\n", "if gene_cols:\n", " missing_genes_pct = linked_data[gene_cols].isna().mean()\n", " genes_with_high_missing = sum(missing_genes_pct > 0.2)\n", " print(f\" Genes with >20% missing: {genes_with_high_missing} out of {len(gene_cols)}\")\n", " \n", " if len(linked_data) > 0:\n", " missing_per_sample = linked_data[gene_cols].isna().mean(axis=1)\n", " samples_with_high_missing = sum(missing_per_sample > 0.05)\n", " print(f\" Samples with >5% missing genes: {samples_with_high_missing} out of {len(linked_data)}\")\n", "\n", "# Handle missing values\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", "trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", "\n", "# 6. Final validation and save\n", "note = \"Dataset contains gene expression data from skeletal muscle samples before and after endurance training, with heart rate measurements.\"\n", "\n", "is_gene_available = len(gene_data) > 0\n", "is_trait_available = True # We've confirmed trait data is available\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=trait_biased, \n", " df=cleaned_data,\n", " note=note\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\")" ] } ], "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 }