{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "1a3f5960", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:09.661957Z", "iopub.status.busy": "2025-03-25T05:55:09.661771Z", "iopub.status.idle": "2025-03-25T05:55:09.831122Z", "shell.execute_reply": "2025-03-25T05:55:09.830715Z" } }, "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 = \"Obesity\"\n", "cohort = \"GSE159809\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obesity\"\n", "in_cohort_dir = \"../../input/GEO/Obesity/GSE159809\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obesity/GSE159809.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obesity/gene_data/GSE159809.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obesity/clinical_data/GSE159809.csv\"\n", "json_path = \"../../output/preprocess/Obesity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "2e67c933", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "abf51bf0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:09.832484Z", "iopub.status.busy": "2025-03-25T05:55:09.832330Z", "iopub.status.idle": "2025-03-25T05:55:09.980190Z", "shell.execute_reply": "2025-03-25T05:55:09.979705Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Adipose tissue adaptations to an 8-week weight loss intervention in younger and older obese men,\"\n", "!Series_summary\t\"Abdominal subcutaneous adipose tissue transcriptomes were analyzed between 11 young and 8 elderly obese men during a lifestyle intervention.\"\n", "!Series_summary\t\"Lifestyle intervention: Individuals underwent 8-weeks of calorie-restriction of 20% below their daily energy requirement aerobic combined to two sessions of resistance exercise per weeks.\"\n", "!Series_overall_design\t\"Two groups,young and elderly; two conditions for each individual, baseline (before lifestyle intervention) and after lifestyle intervention.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['Sex: mix of male and female']}\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": "92206f96", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "76e5b108", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:09.981677Z", "iopub.status.busy": "2025-03-25T05:55:09.981554Z", "iopub.status.idle": "2025-03-25T05:55:09.989926Z", "shell.execute_reply": "2025-03-25T05:55:09.989502Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "No trait data available for extraction and saving.\n" ] } ], "source": [ "# Analyze the background information and sample characteristics\n", "import pandas as pd\n", "import os\n", "\n", "# Step 1: Gene expression data availability\n", "# Based on the series title and summary about adipose tissue transcriptomes, this dataset likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# Step 2: Variable availability and data type conversion\n", "\n", "# Sample Characteristics Dictionary provided shows:\n", "# {0: ['Sex: mix of male and female']}\n", "# Background info mentions two groups (young and elderly) and two conditions (baseline and after intervention)\n", "\n", "# 2.1 Data Availability\n", "# For trait (Obesity-related weight loss intervention):\n", "# The background mentions before/after lifestyle intervention - this appears to be the main trait\n", "# However, we don't see it in the sample characteristics dictionary\n", "trait_row = None\n", "\n", "# For age:\n", "# The background mentions young vs elderly groups\n", "# But we don't see it in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# For gender:\n", "# This is in the sample characteristics dictionary at key 0\n", "gender_row = 0\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert intervention status to binary (0 for baseline, 1 for after intervention).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if 'baseline' in value or 'before' in value or 'pre' in value:\n", " return 0\n", " elif 'after' in value or 'post' in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to binary (0 for young, 1 for elderly).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if 'young' in value:\n", " return 0\n", " elif 'old' in value or 'elder' in value or 'elderly' in value:\n", " return 1\n", " else:\n", " try:\n", " # Try to extract numeric age if available\n", " import re\n", " age_match = re.search(r'(\\d+)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " else:\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " # Handle \"mix of male and female\" case\n", " elif 'mix' in value:\n", " return None # Cannot determine individual gender from this value\n", " else:\n", " return None\n", "\n", "# Step 3: Save metadata\n", "# Initial filtering on usability\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", "# Step 4: Clinical Feature Extraction\n", "# Skip this step since trait_row is None (clinical trait data not available for our study)\n", "if trait_row is not None:\n", " # Get the clinical data\n", " try:\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"), index_col=0)\n", " \n", " selected_clinical = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the clinical data\n", " print(\"Selected Clinical Features Preview:\")\n", " print(preview_df(selected_clinical))\n", " \n", " # Save clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical.to_csv(out_clinical_data_file)\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(\"No clinical data available for extraction and saving.\")\n", "else:\n", " print(\"No trait data available for extraction and saving.\")\n" ] }, { "cell_type": "markdown", "id": "7a3a0cc1", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "ec7c31bc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:09.991307Z", "iopub.status.busy": "2025-03-25T05:55:09.991188Z", "iopub.status.idle": "2025-03-25T05:55:10.226400Z", "shell.execute_reply": "2025-03-25T05:55:10.225753Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074',\n", " 'A_23_P100127', 'A_23_P100141', 'A_23_P100189', 'A_23_P100196',\n", " 'A_23_P100203', 'A_23_P100220', 'A_23_P100240', 'A_23_P10025',\n", " 'A_23_P100292', 'A_23_P100315', 'A_23_P100326', 'A_23_P100344',\n", " 'A_23_P100355', 'A_23_P100386', 'A_23_P100392', 'A_23_P100420'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the file paths again to access the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data from the matrix_file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n", "print(\"First 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "8b70163b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "6a624e90", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:10.228233Z", "iopub.status.busy": "2025-03-25T05:55:10.228103Z", "iopub.status.idle": "2025-03-25T05:55:10.230883Z", "shell.execute_reply": "2025-03-25T05:55:10.230343Z" } }, "outputs": [], "source": [ "# These identifiers with format \"A_23_P...\" are Agilent microarray probe IDs, not human gene symbols.\n", "# They need to be mapped to official gene symbols for meaningful biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "9ce400c5", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a9285c41", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:10.232780Z", "iopub.status.busy": "2025-03-25T05:55:10.232639Z", "iopub.status.idle": "2025-03-25T05:55:11.491136Z", "shell.execute_reply": "2025-03-25T05:55:11.490482Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Platform ID: GPL13497\n", "Platform files found: []\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Found 1 potential mapping sections\n", "Section 1 first 5 lines:\n", "ID\tSPOT_ID\tCONTROL_TYPE\tREFSEQ\tGB_ACC\tGENE\tGENE_SYMBOL\tGENE_NAME\tUNIGENE_ID\tENSEMBL_ID\tTIGR_ID\tACCESSION_STRING\tCHROMOSOMAL_LOCATION\tCYTOBAND\tDESCRIPTION\tGO_ID\tSEQUENCE\n", "(+)E1A_r60_1\t(+)E1A_r60_1\tpos\n", "(+)E1A_r60_3\t(+)E1A_r60_3\tpos\n", "(+)E1A_r60_a104\t(+)E1A_r60_a104\tpos\n", "(+)E1A_r60_a107\t(+)E1A_r60_a107\tpos\n", "Total lines in section 1: 34185\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Found 2337 lines potentially containing probe-gene mappings\n", "A_23_P100189\tA_23_P100189\tFALSE\tNM_002761\tNM_002761\t5619\tPRM1\tprotamine 1\tHs.2909\tENST00000312511\t\tref|NM_002761|ens|ENST00000312511|gb|Y00443|gb|AY651260\tchr16:11374862-11374803\ths|16p13.13\tHomo sapiens protamine 1 (PRM1), mRNA [NM_002761]\tGO:0000786(nucleosome)|GO:0003677(DNA binding)|GO:0005634(nucleus)|GO:0005654(nucleoplasm)|GO:0005694(chromosome)|GO:0006323(DNA packaging)|GO:0006997(nucleus organization)|GO:0007275(multicellular organismal development)|GO:0007283(spermatogenesis)|GO:0007286(spermatid development)|GO:0030154(cell differentiation)|GO:0030261(chromosome condensation)\tGTAGAAGACACTAATTGCACAAAATAGCACATCCACCAAACTCCTGCCTGAGAATGTTAC\n", "A_23_P100392\tA_23_P100392\tFALSE\tNM_007108\tNM_007108\t6923\tTCEB2\ttranscription elongation factor B (SIII), polypeptide 2 (18kDa, elongin B)\tHs.172772\tENST00000409906\t\tref|NM_007108|ref|NM_207013|ens|ENST00000409906|ens|ENST00000262306\tchr16:2821589-2821530\ths|16p13.3\tHomo sapiens transcription elongation factor B (SIII), polypeptide 2 (18kDa, elongin B) (TCEB2), transcript variant 1, mRNA [NM_007108]\tGO:0005515(protein binding)|GO:0005634(nucleus)|GO:0005654(nucleoplasm)|GO:0005829(cytosol)|GO:0006355(regulation of transcription, DNA-dependent)|GO:0006366(transcription from RNA polymerase II promoter)|GO:0006368(transcription elongation from RNA polymerase II promoter)|GO:0006461(protein complex assembly)|GO:0010467(gene expression)|GO:0016032(viral reproduction)|GO:0050434(positive regulation of viral transcription)\tCAGACGATGGCCAAGAGCAGAAACACAAGCTGGAGCCAGTGTCCTGGTTTGACAGCATGT\n", "A_23_P100660\tA_23_P100660\tFALSE\tNM_002615\tNM_002615\t5176\tSERPINF1\tserpin peptidase inhibitor, clade F (alpha-2 antiplasmin, pigment epithelium derived factor), member 1\tHs.532768\tENST00000254722\t\tref|NM_002615|ens|ENST00000254722|gb|AK315344|gb|BT007222\tchr17:1680668-1680727\ths|17p13.3\tHomo sapiens serpin peptidase inhibitor, clade F (alpha-2 antiplasmin, pigment epithelium derived factor), member 1 (SERPINF1), mRNA [NM_002615]\tGO:0001822(kidney development)|GO:0004867(serine-type endopeptidase inhibitor activity)|GO:0005576(extracellular region)|GO:0005615(extracellular space)|GO:0007275(multicellular organismal development)|GO:0007568(aging)|GO:0007614(short-term memory)|GO:0008283(cell proliferation)|GO:0010951(negative regulation of endopeptidase activity)|GO:0016525(negative regulation of angiogenesis)|GO:0030162(regulation of proteolysis)|GO:0031012(extracellular matrix)|GO:0032526(response to retinoic acid)|GO:0042470(melanosome)|GO:0050728(negative regulation of inflammatory response)|GO:0050769(positive regulation of neurogenesis)|GO:0051384(response to glucocorticoid stimulus)|GO:0060770(negative regulation of epithelial cell proliferation involved in prostate gland development)\tCTTCGTACTGAGGGACACAGACACAGGGGCCCTTCTCTTCATTGGCAAGATTCTGGACCC\n", "A_23_P100704\tA_23_P100704\tFALSE\tNM_139033\tNM_139033\t5598\tMAPK7\tmitogen-activated protein kinase 7\tHs.150136\t\t\tref|NM_139033|ref|NM_002749|ref|NM_139034|ref|NM_139032\tchr17:19286634-19286693\ths|17p11.2\tHomo sapiens mitogen-activated protein kinase 7 (MAPK7), transcript variant 1, mRNA [NM_139033]\tGO:0000166(nucleotide binding)|GO:0002224(toll-like receptor signaling pathway)|GO:0002755(MyD88-dependent toll-like receptor signaling pathway)|GO:0002756(MyD88-independent toll-like receptor signaling pathway)|GO:0004674(protein serine/threonine kinase activity)|GO:0004707(MAP kinase activity)|GO:0005515(protein binding)|GO:0005524(ATP binding)|GO:0005634(nucleus)|GO:0005654(nucleoplasm)|GO:0005737(cytoplasm)|GO:0005829(cytosol)|GO:0006915(apoptosis)|GO:0007049(cell cycle)|GO:0007165(signal transduction)|GO:0008063(Toll signaling pathway)|GO:0018105(peptidyl-serine phosphorylation)|GO:0030154(cell differentiation)|GO:0034130(toll-like receptor 1 signaling pathway)|GO:0034134(toll-like receptor 2 signaling pathway)|GO:0034138(toll-like receptor 3 signaling pathway)|GO:0034142(toll-like receptor 4 signaling pathway)|GO:0045087(innate immune response)|GO:0045765(regulation of angiogenesis)|GO:0046777(protein autophosphorylation)|GO:0048011(nerve growth factor receptor signaling pathway)|GO:0051403(stress-activated MAPK cascade)|GO:0051534(negative regulation of NFAT protein import into nucleus)|GO:0070375(BMK cascade)|GO:0071560(cellular response to transforming growth factor beta stimulus)\tGTGAGGCTCGGCTTGGATTATTCTGCAGGTTCATCTCAGACCCACCTTTCAGCCTTAAGC\n", "A_23_P101084\tA_23_P101084\tFALSE\tNM_032598\tNM_032598\t84690\tSPATA22\tspermatogenesis associated 22\tHs.351068\t\t\tref|NM_032598|ref|NM_001170698|ref|NM_001170697|ref|NM_001170695\tchr17:3346555-3346496\ths|17p13.2\tHomo sapiens spermatogenesis associated 22 (SPATA22), transcript variant 2, mRNA [NM_032598]\t\tTTCAGCTGTTACACCTGGCCCATATTATTCGAAGACTTTTCTTATGAGGGATGGGAAAAA\n", "\n", "Let's examine the gene data itself to see if it contains gene symbols:\n", " GSM4847790 GSM4847791 GSM4847792 GSM4847793 GSM4847794 \\\n", "ID \n", "A_23_P100001 -1.713666 -1.811083 -1.027143 -1.358072 -1.625416 \n", "A_23_P100022 0.173474 0.556548 0.695149 0.722535 0.731266 \n", "A_23_P100056 0.963437 0.897981 1.268086 0.616434 0.776272 \n", "A_23_P100074 -0.318198 -0.196503 -0.293632 -0.561407 -0.374687 \n", "A_23_P100127 -0.001519 0.218458 0.195460 0.002374 -0.089716 \n", "\n", " GSM4847795 GSM4847796 GSM4847797 GSM4847798 GSM4847799 ... \\\n", "ID ... \n", "A_23_P100001 -1.447978 -1.496623 -1.586615 -1.392617 -1.225359 ... \n", "A_23_P100022 0.654983 0.665250 0.257254 0.528952 0.463308 ... \n", "A_23_P100056 0.844883 1.118406 0.792798 0.855713 1.121034 ... \n", "A_23_P100074 -0.590901 -0.413525 -0.623469 -0.358888 -0.298866 ... \n", "A_23_P100127 0.034524 -0.097763 -0.068570 0.055725 -0.022660 ... \n", "\n", " GSM4847818 GSM4847819 GSM4847820 GSM4847821 GSM4847822 \\\n", "ID \n", "A_23_P100001 -1.367126 -1.129795 -1.205182 -1.593181 -1.032889 \n", "A_23_P100022 0.658933 0.727375 0.618572 0.258430 0.311905 \n", "A_23_P100056 0.876413 0.486050 1.269938 0.873653 0.784697 \n", "A_23_P100074 -0.305192 -0.350790 -0.364535 -0.425702 -0.428725 \n", "A_23_P100127 0.016459 -0.116834 -0.189779 0.232211 0.111959 \n", "\n", " GSM4847823 GSM4847824 GSM4847825 GSM4847826 GSM4847827 \n", "ID \n", "A_23_P100001 -1.052593 -1.307624 -1.456393 -0.703123 -1.161511 \n", "A_23_P100022 1.056521 0.313320 -0.181048 0.214718 0.748040 \n", "A_23_P100056 0.653640 1.314327 0.910272 0.925726 0.572796 \n", "A_23_P100074 -0.541513 -0.072539 -0.023929 -0.195511 -0.275570 \n", "A_23_P100127 0.123913 -0.070964 0.049087 -0.019830 0.265722 \n", "\n", "[5 rows x 38 columns]\n", "\n", "Fallback approach needed: We need to access platform GPL13497 annotation separately\n", "For now, we'll continue with the probe IDs, and in later steps we can map them to gene symbols\n", "\n", "Created a simple annotation dataframe with probe IDs:\n", "{'ID': ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127']}\n" ] } ], "source": [ "# The gene annotation doesn't contain gene symbol information for the probes\n", "# Let's try a different approach to find the platform annotation\n", "\n", "# First, let's check the platform ID from the SOFT file\n", "platform_id = None\n", "with gzip.open(soft_file, 'rt') as f:\n", " for line in f:\n", " if line.startswith(\"^PLATFORM\"):\n", " platform_id = line.strip().split(\"=\")[1].strip()\n", " break\n", "\n", "print(f\"Platform ID: {platform_id}\")\n", "\n", "# Since we identified the platform as GPL13497, we need to find the mapping information\n", "# Let's check if there's a separate platform file in the cohort directory\n", "platform_files = [f for f in os.listdir(in_cohort_dir) if 'GPL13497' in f or 'platform' in f.lower()]\n", "print(f\"Platform files found: {platform_files}\")\n", "\n", "# If we don't find a separate platform file, let's see if the mapping is in the SOFT file but in a different format\n", "# We'll search for sections that might contain probe-to-gene mappings\n", "mapping_sections = []\n", "with gzip.open(soft_file, 'rt') as f:\n", " current_section = []\n", " in_mapping_section = False\n", " \n", " for line in f:\n", " line = line.strip()\n", " if line.startswith(\"!platform_table_begin\") or line.startswith(\"!Platform_table_begin\"):\n", " in_mapping_section = True\n", " current_section = []\n", " elif line.startswith(\"!platform_table_end\") or line.startswith(\"!Platform_table_end\"):\n", " in_mapping_section = False\n", " if current_section:\n", " mapping_sections.append(current_section)\n", " elif in_mapping_section:\n", " current_section.append(line)\n", "\n", "print(f\"Found {len(mapping_sections)} potential mapping sections\")\n", "\n", "# If we found mapping sections, let's examine them\n", "if mapping_sections:\n", " for i, section in enumerate(mapping_sections):\n", " print(f\"Section {i+1} first 5 lines:\")\n", " for line in section[:5]:\n", " print(line)\n", " print(f\"Total lines in section {i+1}: {len(section)}\")\n", "\n", "# If we still don't have the mapping, let's look for any sections containing probe IDs and gene symbols\n", "# We'll search for probe patterns like A_23_P100001 that we saw in the gene data\n", "import re\n", "\n", "probe_pattern = re.compile(r'A_23_P\\d+')\n", "genes_and_probes = []\n", "\n", "with gzip.open(soft_file, 'rt') as f:\n", " for line in f:\n", " if probe_pattern.search(line) and ('gene' in line.lower() or 'symbol' in line.lower()):\n", " genes_and_probes.append(line.strip())\n", "\n", "print(f\"Found {len(genes_and_probes)} lines potentially containing probe-gene mappings\")\n", "for line in genes_and_probes[:5]:\n", " print(line)\n", "\n", "# Let's try to extract annotation from the gene_data\n", "print(\"\\nLet's examine the gene data itself to see if it contains gene symbols:\")\n", "print(gene_data.head())\n", "\n", "# As a fallback, we can use platform information from GEO to manually create the mapping\n", "# For Agilent GPL13497, we know it's a common human gene expression microarray\n", "# We'll need to download or access this platform's annotation separately\n", "print(\"\\nFallback approach needed: We need to access platform GPL13497 annotation separately\")\n", "print(\"For now, we'll continue with the probe IDs, and in later steps we can map them to gene symbols\")\n", "\n", "# Create a simplified annotation dataframe with just the probe IDs from gene_data\n", "id_column = 'ID' # Using the name of the index in gene_data\n", "probe_ids = pd.DataFrame(gene_data.index).reset_index(drop=True)\n", "\n", "print(\"\\nCreated a simple annotation dataframe with probe IDs:\")\n", "print(preview_df(probe_ids))\n" ] }, { "cell_type": "markdown", "id": "eb93a10c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "c37aa8c4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:11.493075Z", "iopub.status.busy": "2025-03-25T05:55:11.492939Z", "iopub.status.idle": "2025-03-25T05:55:13.020096Z", "shell.execute_reply": "2025-03-25T05:55:13.019440Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping data preview (first 5 rows):\n", "{'ID': ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127'], 'Gene': ['FAM174B', 'SV2B', 'RBPMS2', 'AVEN', 'CASC5'], 'num_genes': [1, 1, 1, 1, 1]}\n", "\n", "Converted gene expression data preview:\n", "{'GSM4847790': [-5.764699319104582, -0.589637109932678, -3.65899480015227, -0.766907820788277, 0.0031521261184095], 'GSM4847791': [-5.084394785758903, 0.245011071656049, -3.93083850415671, -0.858149965855456, -0.132796092924961], 'GSM4847792': [-5.324133218015119, -0.331121975580139, -3.76917843988412, -1.08089825118244, -0.0221959965676392], 'GSM4847793': [-5.139483793512776, -0.261133235359323, -3.64531518306439, -1.25063532844804, -0.0467902729168449], 'GSM4847794': [-5.2449196345753935, 0.0990713459250179, -3.8062076232237, -0.617110550432826, -0.0167349383904996], 'GSM4847795': [-5.5069333272749015, 0.239607115338824, -3.92822766472244, -0.99562629434523, 0.005496001536267], 'GSM4847796': [-5.25563679057503, -0.461558335863026, -3.78694545305259, -1.07214565818222, -0.0637837173868417], 'GSM4847797': [-5.540995151228506, -0.370032583426446, -3.91965513803778, -1.03336968806082, 0.0923263463102402], 'GSM4847798': [-5.408088295844423, -0.044301515701348, -3.78892818842235, -0.962080145547725, 0.0108107347217398], 'GSM4847799': [-4.889221124090806, 0.108395585273986, -3.83812578588603, -0.932872156382047, 0.0099307692423014], 'GSM4847800': [-5.096846230849811, -0.251617092855954, -3.77215520442436, -0.872989850132986, -0.119192545616785], 'GSM4847801': [-4.879140905750509, 0.0246682208587159, -3.8826880011254, -1.22908495249694, 0.0754552228570418], 'GSM4847802': [-5.322196303263509, 0.179808913592053, -3.73270445208419, -0.797838035356794, -0.0159750178647015], 'GSM4847803': [-5.1314349478217895, 0.0982224376107475, -3.78387490912832, -0.661577636919282, -0.0726724060102017], 'GSM4847804': [-4.822893266831084, 0.675358929149873, -3.81856184452303, -0.839155867441618, 0.0906047980176672], 'GSM4847805': [-6.0761621469437905, 0.416867361620881, -3.76373422972844, -1.14025065736958, 0.0729049338889951], 'GSM4847806': [-5.610157383621986, -0.0579390729436747, -3.70806418111865, -0.881189275636364, -0.0456580464694213], 'GSM4847807': [-5.868100796269169, 0.374851597937183, -3.67511817836978, -1.18284648374236, -0.126377708993799], 'GSM4847808': [-5.545178551014693, 0.209390658593375, -3.53883838049011, -1.08097154794457, -0.137194802101904], 'GSM4847809': [-5.937740457929549, 0.10005089360875, -3.68745847916704, -0.868590357432952, 0.0578456971940312], 'GSM4847810': [-5.249260266863653, -0.522682801061744, -3.79769088026673, -1.09272634068267, -0.233009801726235], 'GSM4847811': [-6.217193844666028, -0.402906776679347, -4.09105582495144, -1.15233434780328, -0.55668539202962], 'GSM4847812': [-4.972840595660701, -0.0918611442762975, -3.79527869745549, -0.699461587999713, -0.246797445861331], 'GSM4847813': [-5.507009672562096, 0.0871240758283635, -3.92063659295385, -0.573389944654208, -0.110857652286867], 'GSM4847814': [-5.126683313686332, -0.324742199586988, -3.94902340957772, -1.01909205937464, 0.020644172790225], 'GSM4847815': [-5.914398220582207, 0.168296526100118, -3.97614704727732, -1.03916360603402, 0.324935302708718], 'GSM4847816': [-4.962791120095739, 0.190477383552574, -3.70621721886238, -1.17300034954158, -0.291214664462763], 'GSM4847817': [-5.254269277422642, -0.0226492092057739, -3.80468260997052, -0.858644633881348, -0.254726169013023], 'GSM4847818': [-4.683704218858249, 0.121175463787175, -3.8336521500508, -0.542757444478244, -0.0125025487099438], 'GSM4847819': [-5.8641554416145425, 0.17780749503288, -3.82733332659882, -0.462583584430135, 0.168689616114235], 'GSM4847820': [-4.44149953975575, 0.0207947353476773, -3.71386929307558, -0.970561828284765, 0.131117340098735], 'GSM4847821': [-4.676221625946568, 0.0633598930009758, -3.8509356521118, -0.872771550610624, 0.202950721350476], 'GSM4847822': [-5.553061325205095, -0.181631832572219, -3.78200587074782, -0.911501648374011, 0.210216154102504], 'GSM4847823': [-4.840820110162124, 0.25393618965355, -3.75002462736857, -1.11313189506791, 0.420137142310316], 'GSM4847824': [-5.538606708617721, 0.246295255484111, -3.79411274461293, -1.21575710205905, 0.267377602398244], 'GSM4847825': [-5.391800980099377, -0.0570512372548678, -3.85004419824447, -1.00900844064067, 0.025903799714214], 'GSM4847826': [-5.309889188323428, -0.450753486036313, -3.70389373513658, -1.07473048138505, 0.547400423357692], 'GSM4847827': [-5.285879085756482, 0.141004865383374, -3.70475544521499, -0.816618729976285, -0.0533574008174305]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Obesity/gene_data/GSE159809.csv\n" ] } ], "source": [ "# From the gene annotation section in the output, we can see this table structure:\n", "# ID | SPOT_ID | CONTROL_TYPE | REFSEQ | GB_ACC | GENE | GENE_SYMBOL | GENE_NAME | ...\n", "\n", "# 1. Extract the probe-to-gene mapping from the platform annotation in the SOFT file\n", "# Based on the section output we saw, we need the ID and GENE_SYMBOL columns\n", "mapping_data = None\n", "with gzip.open(soft_file, 'rt') as f:\n", " platform_section = False\n", " header = None\n", " rows = []\n", " \n", " for line in f:\n", " line = line.strip()\n", " if line.startswith(\"!platform_table_begin\") or line.startswith(\"!Platform_table_begin\"):\n", " platform_section = True\n", " continue\n", " elif line.startswith(\"!platform_table_end\") or line.startswith(\"!Platform_table_end\"):\n", " platform_section = False\n", " continue\n", " \n", " if platform_section:\n", " if header is None:\n", " header = line.split('\\t')\n", " # Find the index of ID and GENE_SYMBOL columns\n", " id_idx = header.index('ID')\n", " symbol_idx = header.index('GENE_SYMBOL')\n", " else:\n", " parts = line.split('\\t')\n", " if len(parts) > max(id_idx, symbol_idx):\n", " rows.append([parts[id_idx], parts[symbol_idx]])\n", " \n", " # Create a DataFrame with the mapping data\n", " mapping_data = pd.DataFrame(rows, columns=['ID', 'Gene'])\n", "\n", "# Clean up the mapping data - remove rows where Gene is empty\n", "mapping_data = mapping_data[mapping_data['Gene'] != '']\n", "\n", "# 2. Convert the mapping data to proper format for our gene expression analysis\n", "# Each probe may map to multiple genes (separated by '|')\n", "# We'll split these into separate rows\n", "mapping_data['Gene'] = mapping_data['Gene'].apply(lambda x: [g for g in x.split('|') if g])\n", "mapping_data = mapping_data.explode('Gene')\n", "\n", "# Calculate the number of genes per probe for later normalization\n", "probe_to_gene_count = mapping_data.groupby('ID').size().to_dict()\n", "mapping_data['num_genes'] = mapping_data['ID'].map(probe_to_gene_count)\n", "\n", "print(f\"Mapping data preview (first 5 rows):\")\n", "print(preview_df(mapping_data.head()))\n", "\n", "# 3. Convert probe-level measurements to gene expression data\n", "# First, ensure gene_data has the ID as regular column, not index\n", "gene_data_reset = gene_data.reset_index()\n", "\n", "# Merge with mapping data to assign probe values to genes\n", "merged_data = pd.merge(mapping_data, gene_data_reset, on='ID', how='inner')\n", "\n", "# Divide by number of genes per probe (equally distributing signal)\n", "expr_cols = merged_data.columns.drop(['ID', 'Gene', 'num_genes'])\n", "for col in expr_cols:\n", " merged_data[col] = merged_data[col] / merged_data['num_genes']\n", "\n", "# Sum values by gene\n", "gene_data = merged_data.groupby('Gene')[expr_cols].sum()\n", "\n", "print(\"\\nConverted gene expression data preview:\")\n", "print(preview_df(gene_data.head()))\n", "\n", "# Save the gene expression data to CSV\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\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "13510c7f", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "7bec7091", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:55:13.022010Z", "iopub.status.busy": "2025-03-25T05:55:13.021846Z", "iopub.status.idle": "2025-03-25T05:55:13.790140Z", "shell.execute_reply": "2025-03-25T05:55:13.789493Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Obesity/gene_data/GSE159809.csv\n", "No trait data available for this dataset. Proceeding with gene expression data only.\n", "Created placeholder data structure for validation purposes\n", "The trait 'Obesity' is severely biased in this dataset (all subjects have obesity).\n", "No demographic features (Age, Gender) available to evaluate for bias.\n", "Dataset usability status: False\n", "Dataset is not usable for obesity trait-gene association studies.\n" ] } ], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# Since trait_row is None (as determined in Step 2), we don't have clinical data to work with\n", "print(\"No trait data available for this dataset. Proceeding with gene expression data only.\")\n", "\n", "# Create a minimal DataFrame to use for validation\n", "# Since there's no clinical data, we'll create a minimal DataFrame with the gene expression data\n", "# This allows us to use the validate_and_save_cohort_info function without clinical features\n", "sample_ids = normalized_gene_data.columns.tolist()\n", "linked_data = normalized_gene_data.T # Transpose so samples are rows\n", "\n", "# Add a placeholder Obesity column to allow validation functions to run\n", "linked_data['Obesity'] = 1 # All subjects have obesity (constant trait)\n", "print(\"Created placeholder data structure for validation purposes\")\n", "\n", "# Determine trait is biased (no variability - all subjects have obesity)\n", "is_trait_biased = True\n", "print(\"The trait 'Obesity' is severely biased in this dataset (all subjects have obesity).\")\n", "\n", "# No demographic features to evaluate for bias since they aren't available\n", "print(\"No demographic features (Age, Gender) available to evaluate for bias.\")\n", "\n", "# Conduct final validation\n", "note = \"This dataset contains gene expression data from obese individuals only, making it unsuitable for obesity vs. non-obesity association studies. It appears to be a study of pre/post intervention in obese individuals, but that trait information is not clearly encoded in the available 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=is_gene_available, \n", " is_trait_available=is_trait_available, # False as determined in Step 2\n", " is_biased=is_trait_biased,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "print(f\"Dataset usability status: {is_usable}\")\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset is not usable for obesity trait-gene association studies.\")" ] } ], "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 }