{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6693a91c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:05:42.432175Z", "iopub.status.busy": "2025-03-25T04:05:42.432070Z", "iopub.status.idle": "2025-03-25T04:05:42.623563Z", "shell.execute_reply": "2025-03-25T04:05:42.623223Z" } }, "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 = \"Stroke\"\n", "cohort = \"GSE68526\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Stroke\"\n", "in_cohort_dir = \"../../input/GEO/Stroke/GSE68526\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Stroke/GSE68526.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Stroke/gene_data/GSE68526.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Stroke/clinical_data/GSE68526.csv\"\n", "json_path = \"../../output/preprocess/Stroke/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ce1ff08c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0cc2ce5e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:05:42.625013Z", "iopub.status.busy": "2025-03-25T04:05:42.624863Z", "iopub.status.idle": "2025-03-25T04:05:42.830137Z", "shell.execute_reply": "2025-03-25T04:05:42.829767Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Peripheral blood transcriptome profiles from an RNA Pilot Study within the United States Health and Retirement Study (HRS)\"\n", "!Series_summary\t\"Individual differences in peripheral blood transcriptomes in older adults as a function of demographic, socio-economic, psychological, and health history characteristics.\"\n", "!Series_overall_design\t\"Gene expression profiling was carried out on peripheral blood RNA samples collected from 121 community dwelling older adults participating in the United States Health and Retirement Study. In addition to basic demographic characteristics (age, sex, race/ethnicity), participants were also assessed on health-related characteristics (body mass index/BMI; history of smoking or heavy alcohol consumption; history of chronic illnesses such as diabetes, cardiovascular disease, cancer, stroke), household annual income (log transformed), and measures of loneliness (UCLA Loneliness Scale; Russell D, Peplau LA, Cutrona CE: The revised UCLA Loneliness Scale: concurrent and discriminant validity evidence. J Pers Soc Psychol 1980, 39:472-480; higher values indicate greater loneliness) and purpose in life (PWB_Purpose; Purpose scale of the Ryff Scales of Psychological Well-being; Ryff CD (1989) Happiness is everything, or is it? Explorations on the meaning of psychological well-being. J. Pers Soc. Psychol 57: 1069-1081; higher values indicate greater experience of purpose in life). Additional analyses examined measures of optimism and pessimism (6 items from the Life Orientation Test; Scheier MF Carver CS Bridges MW (1994) Distinguishing optimism from neuroticism (and trait anxiety, self-mastery, and self-esteem): A reevaluation of the Life Orientation Test. J Pers Soc Psychol 67:1063-1078; higher values indicating greater optimism or pessimism), anxiety symptoms (5 items from Beck Anxiety Inventory; Beck AT et al (1988) An inventory for measuring clinical anxiety: Psychometric properties. J Consult Clin Psychol 56:893-897; higher values indicating greater anxietn), depressive symptoms (CESD; Center for Epidemiologic Studies Depression Scale; Radloff LS (1977) The CES-D scale: A self-report depression scale for research in the general population. Applied Psychol Meas 1:386-401; higher values indicating greater depression), life satisfaction (Diener E et al (1985) The Satisfaction With Life Scale. J Pers Assess 49:71-75; higher values indicate greater life satisfaction), and positive affect (PA) and negative affect (NA; Watson D et al (1988) Development and validation of brief measures of positive and negative affect: The PANAS scales. J Pers Soc Psychol 54:1063-1070; higher values indicate greater positive or negative affect).\"\n", "!Series_overall_design\t\"Binary characteristics are coded yes=1 and no=0.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['age (yrs): 79', 'age (yrs): 76', 'age (yrs): 70', 'age (yrs): 65', 'age (yrs): 64', 'age (yrs): 75', 'age (yrs): 66', 'age (yrs): 93', 'age (yrs): 69', 'age (yrs): 67', 'age (yrs): 77', 'age (yrs): 74', 'age (yrs): 73', 'age (yrs): 80', 'age (yrs): 68', 'age (yrs): 83', 'age (yrs): 87', 'age (yrs): 81', 'age (yrs): 84', 'age (yrs): 55', 'age (yrs): 62', 'age (yrs): 58', 'age (yrs): 60', 'age (yrs): 56', 'age (yrs): 86', 'age (yrs): 78', 'age (yrs): 48', 'age (yrs): 82', 'age (yrs): 95', 'age (yrs): 71'], 1: ['female: 0', 'female: 1'], 2: ['black: 0', 'black: 1'], 3: ['hispanic: 0', 'hispanic: 1'], 4: ['bmi: 22.7', 'bmi: 29.1', 'bmi: 25.8', 'bmi: 24.8', 'bmi: 42.1', 'bmi: 29.6', 'bmi: 21.4', 'bmi: 32.7', 'bmi: 30.7', 'bmi: 29.2', 'bmi: 34.0', 'bmi: 44.3', 'bmi: 28.7', 'bmi: 27.4', 'bmi: 30.6', 'bmi: 31.3', 'bmi: 30.0', 'bmi: 25.1', 'bmi: 26.4', 'bmi: 21.6', 'bmi: 18.6', 'bmi: 24.1', 'bmi: 22.9', 'bmi: 28.6', 'bmi: 25.0', 'bmi: 27.5', 'bmi: 25.5', 'bmi: 23.7', 'bmi: 23.0', 'bmi: 28.5'], 5: ['diabcvdcastr: 1', 'diabcvdcastr: 0'], 6: ['ln_hh_income: 16.03', 'ln_hh_income: 15.49', 'ln_hh_income: 15.34', 'ln_hh_income: 15.52', 'ln_hh_income: 16.41', 'ln_hh_income: 14.20', 'ln_hh_income: 18.09', 'ln_hh_income: 13.57', 'ln_hh_income: 16.29', 'ln_hh_income: 14.64', 'ln_hh_income: 15.28', 'ln_hh_income: 15.30', 'ln_hh_income: 15.93', 'ln_hh_income: 15.02', 'ln_hh_income: 16.93', 'ln_hh_income: 14.44', 'ln_hh_income: 16.10', 'ln_hh_income: 14.22', 'ln_hh_income: 13.18', 'ln_hh_income: 14.90', 'ln_hh_income: 12.97', 'ln_hh_income: 16.36', 'ln_hh_income: 16.14', 'ln_hh_income: 14.91', 'ln_hh_income: 13.71', 'ln_hh_income: 15.99', 'ln_hh_income: 13.77', 'ln_hh_income: 15.46', 'ln_hh_income: 13.86', 'ln_hh_income: 16.42'], 7: ['smoke: 1', 'smoke: 0'], 8: ['alcohol: 0', 'alcohol: 1', 'alcohol: missing'], 9: ['loneliness: 1.00', 'loneliness: 2.00', 'loneliness: 1.67', 'loneliness: 1.33', 'loneliness: 2.67', 'loneliness: missing', 'loneliness: 2.33', 'loneliness: 3.00'], 10: ['pwb_purpose: 4.14', 'pwb_purpose: 6.00', 'pwb_purpose: 5.00', 'pwb_purpose: 5.43', 'pwb_purpose: 3.29', 'pwb_purpose: 5.14', 'pwb_purpose: 4.71', 'pwb_purpose: 5.33', 'pwb_purpose: 4.83', 'pwb_purpose: 2.67', 'pwb_purpose: 5.71', 'pwb_purpose: 5.57', 'pwb_purpose: 5.17', 'pwb_purpose: 3.83', 'pwb_purpose: 4.00', 'pwb_purpose: 5.83', 'pwb_purpose: missing', 'pwb_purpose: 5.29', 'pwb_purpose: 4.17', 'pwb_purpose: 4.43', 'pwb_purpose: 3.17', 'pwb_purpose: 2.57', 'pwb_purpose: 3.50', 'pwb_purpose: 4.86', 'pwb_purpose: 5.50', 'pwb_purpose: 3.67', 'pwb_purpose: 3.71', 'pwb_purpose: 4.50', 'pwb_purpose: 4.33', 'pwb_purpose: 3.86'], 11: ['optimism: 4', 'optimism: 5.66667', 'optimism: 2.66667', 'optimism: 3', 'optimism: 5', 'optimism: 1.66667', 'optimism: 6', 'optimism: 4.66667', 'optimism: 5.33333', 'optimism: 3.66667', 'optimism: missing', 'optimism: 3.33333', 'optimism: 4.33333'], 12: ['pessimism: 1.66667', 'pessimism: 1', 'pessimism: 5', 'pessimism: 4', 'pessimism: 3', 'pessimism: 3.66667', 'pessimism: 2.66667', 'pessimism: 2', 'pessimism: 3.33333', 'pessimism: 2.33333', 'pessimism: 4.33333', 'pessimism: missing', 'pessimism: 6', 'pessimism: 1.33333', 'pessimism: 5.66667', 'pessimism: 4.66667', 'pessimism: 2.5'], 13: ['anxiety: 1', 'anxiety: 1.8', 'anxiety: 1.2', 'anxiety: 1.4', 'anxiety: 2.2', 'anxiety: 1.6', 'anxiety: missing', 'anxiety: 2.8', 'anxiety: 2', 'anxiety: 2.4', 'anxiety: 3.2', 'anxiety: 2.6'], 14: ['cesd: 0', 'cesd: 1', 'cesd: 2', 'cesd: 3', 'cesd: missing', 'cesd: 6', 'cesd: 4', 'cesd: 5', 'cesd: 7', 'cesd: 8'], 15: ['lifesatisfaction: 5.2', 'lifesatisfaction: 7', 'lifesatisfaction: 4.4', 'lifesatisfaction: 5.4', 'lifesatisfaction: 2.6', 'lifesatisfaction: 4.8', 'lifesatisfaction: 6.8', 'lifesatisfaction: 5', 'lifesatisfaction: 1.4', 'lifesatisfaction: 6', 'lifesatisfaction: 2.4', 'lifesatisfaction: 4.6', 'lifesatisfaction: 3.8', 'lifesatisfaction: missing', 'lifesatisfaction: 3', 'lifesatisfaction: 4', 'lifesatisfaction: 3.4', 'lifesatisfaction: 5.6', 'lifesatisfaction: 3.2', 'lifesatisfaction: 6.2', 'lifesatisfaction: 4.2', 'lifesatisfaction: 1.8', 'lifesatisfaction: 1', 'lifesatisfaction: 2.2', 'lifesatisfaction: 6.4', 'lifesatisfaction: 5.33333', 'lifesatisfaction: 5.8', 'lifesatisfaction: 1.2', 'lifesatisfaction: 4.33333', 'lifesatisfaction: 2.8'], 16: ['pa: 4', 'pa: 4.92308', 'pa: 2.84615', 'pa: 4.33333', 'pa: 2.66667', 'pa: 3.61538', 'pa: 4.46154', 'pa: 3.30769', 'pa: 2.16667', 'pa: 3', 'pa: 3.83333', 'pa: 3.84615', 'pa: 2.76923', 'pa: 3.92308', 'pa: missing', 'pa: 5', 'pa: 2.5', 'pa: 4.83333', 'pa: 3.16667', 'pa: 2.83333', 'pa: 4.76923', 'pa: 4.69231', 'pa: 3.33333', 'pa: 2.53846', 'pa: 4.66667', 'pa: 3.5', 'pa: 2.30769', 'pa: 1.5', 'pa: 4.07692', 'pa: 3.46154'], 17: ['na: 1.33333', 'na: 1', 'na: 1.58333', 'na: 1.5', 'na: 2.25', 'na: 2.16667', 'na: 2', 'na: 1.83333', 'na: 1.75', 'na: missing', 'na: 1.45455', 'na: 2.75', 'na: 3', 'na: 1.16667', 'na: 1.41667', 'na: 2.66667', 'na: 1.08333', 'na: 1.66667', 'na: 2.83333', 'na: 1.91667', 'na: 3.09091', 'na: 2.5', 'na: 2.91667', 'na: 1.25']}\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": "1fb0eec6", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "771c337a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:05:42.831603Z", "iopub.status.busy": "2025-03-25T04:05:42.831453Z", "iopub.status.idle": "2025-03-25T04:05:42.838943Z", "shell.execute_reply": "2025-03-25T04:05:42.838616Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Error processing clinical data: name 'get_clinical_data' is not defined\n", "Clinical data processing step skipped.\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "from typing import Optional, Callable, Dict, Any\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this is a peripheral blood transcriptome study\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Examine the sample characteristics for trait, age, and gender\n", "\n", "# Stroke data - need to examine field 5 which contains 'diabcvdcastr'\n", "# This appears to indicate diabetes, cardiovascular disease, cancer, and stroke\n", "trait_row = 5\n", "\n", "# Age is available in row 0\n", "age_row = 0\n", "\n", "# Gender is available in row 1 (coded as female: 0/1)\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait values - diabcvdcastr field contains stroke information\"\"\"\n", " if value is None or pd.isna(value) or 'missing' in str(value).lower():\n", " return None\n", " \n", " # The field 'diabcvdcastr' represents multiple conditions including stroke\n", " # Based on the name 'diabcvdcastr', the 'str' part likely refers to stroke\n", " # We're looking at a binary field (1 = has at least one of these conditions, 0 = none)\n", " try:\n", " # Extract the value after the colon\n", " if ':' in str(value):\n", " val = str(value).split(':', 1)[1].strip()\n", " # Convert to binary (1 = yes, 0 = no)\n", " return int(val)\n", " else:\n", " return int(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous numeric values\"\"\"\n", " if value is None or pd.isna(value) or 'missing' in str(value).lower():\n", " return None\n", " \n", " try:\n", " # Extract the numeric part after the colon\n", " if ':' in str(value):\n", " val = str(value).split(':', 1)[1].strip()\n", " return float(val)\n", " else:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 = female, 1 = male)\"\"\"\n", " if value is None or pd.isna(value) or 'missing' in str(value).lower():\n", " return None\n", " \n", " try:\n", " # The data is coded as 'female: 0' or 'female: 1'\n", " # female: 1 means female (so should be 0 in our coding)\n", " # female: 0 means male (so should be 1 in our coding)\n", " if ':' in str(value):\n", " val = str(value).split(':', 1)[1].strip()\n", " female_indicator = int(val)\n", " # Convert: female indicator of 1 means female (0), 0 means male (1)\n", " return 1 - female_indicator\n", " else:\n", " # If value is just 0 or 1 without the 'female:' prefix\n", " female_indicator = int(value)\n", " return 1 - female_indicator\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "# 3. Save Metadata for initial filtering\n", "# Check if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Only proceed if trait_row is not None (clinical data is available)\n", "if trait_row is not None:\n", " # We need to reconstruct the clinical_data from the sample characteristics information\n", " # that was provided in the previous step\n", " \n", " # First, let's load the clinical data which should be available from previous steps\n", " try:\n", " # Assuming clinical_data is already loaded in this environment\n", " clinical_data = get_clinical_data()\n", " \n", " # Use the function to 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", " # Preview the data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\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, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " print(\"Clinical data processing step skipped.\")\n" ] }, { "cell_type": "markdown", "id": "7929659b", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "f9c0f5cd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:05:42.840110Z", "iopub.status.busy": "2025-03-25T04:05:42.839983Z", "iopub.status.idle": "2025-03-25T04:05:42.850282Z", "shell.execute_reply": "2025-03-25T04:05:42.849979Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Series matrix file not found at ../../input/GEO/Stroke/GSE68526/series_matrix.txt\n", "Clinical feature extraction skipped - trait data not available or clinical data not loaded.\n" ] } ], "source": [ "# Define the helper function missing from the provided code\n", "def get_feature_data(clinical_df, row_id, feature_name, convert_func):\n", " \"\"\"Extract and process a specific feature from clinical data.\"\"\"\n", " feature_data = clinical_df.iloc[row_id:row_id+1, :].copy()\n", " feature_data = feature_data.T\n", " feature_data.columns = [feature_name]\n", " feature_data = feature_data.applymap(convert_func)\n", " return feature_data\n", "\n", "# First, let's try to load the clinical data and properly parse GEO data format\n", "import os\n", "import json\n", "import pandas as pd\n", "import numpy as np\n", "import re\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "is_gene_available = True # Assume gene expression data is available by default\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "clinical_data = None\n", "\n", "# Check for series_matrix.txt file which is the standard format in GEO datasets\n", "series_matrix_file = os.path.join(in_cohort_dir, \"series_matrix.txt\")\n", "if os.path.exists(series_matrix_file):\n", " print(f\"Series matrix file found at {series_matrix_file}\")\n", " \n", " # Parse the series matrix file to extract clinical information\n", " sample_chars = {}\n", " sample_titles = []\n", " \n", " with open(series_matrix_file, 'r') as f:\n", " lines = f.readlines()\n", " \n", " # Extract sample titles\n", " for line in lines:\n", " if line.startswith(\"!Sample_title\"):\n", " titles = line.strip().split('\\t')[1:]\n", " sample_titles = [t.strip('\"') for t in titles]\n", " \n", " # Extract and organize sample characteristics by row\n", " char_lines = [line for line in lines if line.startswith(\"!Sample_characteristics\")]\n", " \n", " for i, line in enumerate(char_lines):\n", " values = line.strip().split('\\t')[1:]\n", " values = [v.strip('\"') for v in values]\n", " sample_chars[i] = values\n", " \n", " # Print the first few values to help identify relevant rows\n", " print(f\"Row {i} sample characteristics: {values[:5]}...\")\n", " \n", " # Create a DataFrame from the sample characteristics\n", " if sample_chars and sample_titles:\n", " sample_chars_df = pd.DataFrame(sample_chars, index=sample_titles).T\n", " clinical_data = sample_chars_df\n", " \n", " # Analyze the rows to identify trait, age, and gender\n", " for i in range(len(clinical_data)):\n", " unique_values = clinical_data.iloc[i].unique()\n", " print(f\"Row {i} unique values: {unique_values[:5]}\")\n", " \n", " # Look for trait information\n", " row_str = ' '.join([str(x).lower() for x in unique_values if str(x) != 'nan'])\n", " if re.search(r'stroke|disease|control|normal|case|patient|diagnosis', row_str):\n", " trait_row = i\n", " print(f\"Identified trait row: {i}\")\n", " \n", " # Look for age information\n", " if re.search(r'age|years|old', row_str):\n", " age_row = i\n", " print(f\"Identified age row: {i}\")\n", " \n", " # Look for gender information\n", " if re.search(r'gender|sex|male|female', row_str):\n", " gender_row = i\n", " print(f\"Identified gender row: {i}\")\n", "else:\n", " print(f\"Series matrix file not found at {series_matrix_file}\")\n", " \n", " # Check for clinical_data.csv as a fallback\n", " clinical_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_file):\n", " clinical_data = pd.read_csv(clinical_file)\n", " print(f\"Clinical data loaded from {clinical_file}\")\n", " \n", " # Similar analysis would be needed here to identify relevant rows\n", " # But without seeing the actual data structure, this is challenging\n", "\n", "# Define conversion functions with proper handling of formats found in GEO data\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 for control, 1 for case).\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " value_str = str(value).lower()\n", " if ':' in value_str:\n", " value_str = value_str.split(':', 1)[1].strip()\n", " \n", " if 'stroke' in value_str or 'case' in value_str or 'patient' in value_str or 'disease' in value_str:\n", " return 1\n", " elif 'control' in value_str or 'healthy' in value_str or 'normal' in value_str:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous number.\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " value_str = str(value).lower()\n", " if ':' in value_str:\n", " value_str = value_str.split(':', 1)[1].strip()\n", " \n", " # Try to extract numeric age\n", " age_match = re.search(r'(\\d+(\\.\\d+)?)', value_str)\n", " if age_match:\n", " try:\n", " return float(age_match.group(1))\n", " except:\n", " return None\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " value_str = str(value).lower()\n", " if ':' in value_str:\n", " value_str = value_str.split(':', 1)[1].strip()\n", " \n", " if 'female' in value_str or 'f' == value_str.strip() or 'woman' in value_str:\n", " return 0\n", " elif 'male' in value_str or 'm' == value_str.strip() or 'man' in value_str:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Determine trait availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Use the library function to validate and save cohort info\n", "initial_validation = 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", "# Only extract clinical features if trait data is available and clinical data exists\n", "if trait_row is not None and clinical_data is not None:\n", " # Extract and process 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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\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, index=True)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"Clinical feature extraction skipped - trait data not available or clinical data not loaded.\")\n" ] }, { "cell_type": "markdown", "id": "3e0bfb0f", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 5, "id": "f095bfeb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:05:42.851343Z", "iopub.status.busy": "2025-03-25T04:05:42.851234Z", "iopub.status.idle": "2025-03-25T04:05:43.256728Z", "shell.execute_reply": "2025-03-25T04:05:43.256387Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Stroke/GSE68526/GSE68526_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (34581, 121)\n", "First 20 gene/probe identifiers:\n", "Index(['7A5', 'A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1',\n", " 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AACSL', 'AADAC',\n", " 'AADACL1', 'AADACL2', 'AADACL3', 'AADACL4'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "7b9b93b1", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 6, "id": "3fda3d84", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:05:43.257906Z", "iopub.status.busy": "2025-03-25T04:05:43.257783Z", "iopub.status.idle": "2025-03-25T04:05:43.259848Z", "shell.execute_reply": "2025-03-25T04:05:43.259535Z" } }, "outputs": [], "source": [ "# Examine the first 20 gene identifiers\n", "# These identifiers (like 'A1BG', 'A2M', 'AAAS') are standard human gene symbols,\n", "# not probe IDs which would typically be numeric or have specific formats (like Affymetrix IDs)\n", "# No mapping is needed as these are already proper human gene symbols\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "f8c7b015", "metadata": {}, "source": [ "### Step 6: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 7, "id": "12e7c918", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:05:43.260837Z", "iopub.status.busy": "2025-03-25T04:05:43.260726Z", "iopub.status.idle": "2025-03-25T04:05:44.779663Z", "shell.execute_reply": "2025-03-25T04:05:44.779084Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene data shape: (34581, 121)\n", "Gene data shape after normalization: (20741, 121)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Stroke/gene_data/GSE68526.csv\n", "No trait data available. Can't proceed with linking clinical and genetic data.\n", "Abnormality detected in the cohort: GSE68526. Preprocessing failed.\n", "Dataset deemed not usable due to missing trait data.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "# Use the gene_data variable that was already loaded in Step 4\n", "print(f\"Original gene data shape: {gene_data.shape}\")\n", "\n", "# Normalize gene symbols\n", "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {gene_data_normalized.shape}\")\n", "\n", "# Save the normalized gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "\n", "# 2. No clinical data available (trait_row is None from previous steps)\n", "# We can't proceed with linking clinical and genetic data\n", "print(\"No trait data available. Can't proceed with linking clinical and genetic data.\")\n", "\n", "# Create a minimal dataframe for validation purposes \n", "# (since we need a valid DataFrame when is_final=True)\n", "empty_df = pd.DataFrame({\"dummy\": [0]})\n", "\n", "# Since trait data is not available, the dataset is not usable for our purposes\n", "# We pass is_biased=True to indicate unusable data\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=False,\n", " is_biased=True, # Setting is_biased to True since missing trait data makes dataset unusable\n", " df=empty_df,\n", " note=\"No stroke-specific trait data available in this dataset. Contains gene expression data from peripheral blood of older adults, but without clear stroke indicators.\"\n", ")\n", "print(\"Dataset deemed not usable due to missing trait data.\")" ] } ], "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 }