File size: 31,891 Bytes
d1894e4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "e1c4e17f",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T05:40:05.671523Z",
"iopub.status.busy": "2025-03-25T05:40:05.671421Z",
"iopub.status.idle": "2025-03-25T05:40:05.837960Z",
"shell.execute_reply": "2025-03-25T05:40:05.837631Z"
}
},
"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 = \"Height\"\n",
"cohort = \"GSE101709\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Height\"\n",
"in_cohort_dir = \"../../input/GEO/Height/GSE101709\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Height/GSE101709.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Height/gene_data/GSE101709.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Height/clinical_data/GSE101709.csv\"\n",
"json_path = \"../../output/preprocess/Height/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "da535d59",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "447b2db5",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T05:40:05.839480Z",
"iopub.status.busy": "2025-03-25T05:40:05.839335Z",
"iopub.status.idle": "2025-03-25T05:40:06.230956Z",
"shell.execute_reply": "2025-03-25T05:40:06.230643Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"Gene expression analysis of Influenza vaccine response in Young and Old - Year 4\"\n",
"!Series_summary\t\"We profiled gene expression from a stratified cohort of subjects to define influenza vaccine response in Young and Old\"\n",
"!Series_overall_design\t\"Differential gene expression by human PBMCs from Healthy Adults receiving Influenza Vaccination (Fluvirin, Novartis). Healthy adults (older >65, younger 21-30 years) were recruited at seasonal Influenza Vaccination clinics organized by Yale University Health Services during October to December of 2013 – 2014 seasons. With informed consent, healthy individuals were recruited as per a protocol approved by Human Investigations Committee of the Yale University School of Medicine. Each subject was evaluated by a screening questionnaire determining self-reported demographic information, height, weight, medications and comorbid conditions. Participants with acute illness two weeks prior to vaccination were excluded from study. Blood samples were collected into BD Vacutainer Sodium Heparin tube at four different time points, once prior to administration of vaccine and three time points after vaccination on days 2, 7 and 28. Peripheral Blood Mononuclear Cells (PBMC) were isolated from heparinized blood using Histopaque 1077 in gradient centrifugation. About 1.0x10^7 freshly isolated PBMC were lysed in Triso and immediately stored in -80C. Total RNA in aqueous phase of Trisol - Chloroform was isolated in an automated QiaCube instrument using miRNeasy according to manufacturer’s instructions. Integrity of RNA samples were assessed by Agilent 2100 BioAnalyser Samples were processed for cRNA generation using Illumina TotalPrep cRNA Amplification Kit and subsequently hybridized to Human HT12-V4.0 BeadChip at Yale Center for Genomic Analysis (YGCA).\"\n",
"!Series_overall_design\t\"\"\n",
"!Series_overall_design\t\"The current data set, together with GSE59654, GSE59635, GSE59743, and GSE101710, represents subsets of the same overall study\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['subject status: Healthy Adults receiving Influenza Vaccination'], 1: ['age group: Frail', 'age group: Older', 'age group: Young'], 2: ['blood draw date: after vaccination day 2', 'blood draw date: after vaccination day 7', 'blood draw date: after vaccination day 28', 'blood draw date: day 0; prior to administration of vaccine', 'blood draw date: after vaccination day 43'], 3: ['cell type: Peripheral Blood Mononuclear Cells (PBMC)'], 4: ['immport_expsamp_acc: ImmPort:ES1167274', 'immport_expsamp_acc: ImmPort:ES1167275', 'immport_expsamp_acc: ImmPort:ES1167276', 'immport_expsamp_acc: ImmPort:ES1167277', 'immport_expsamp_acc: ImmPort:ES1167278', 'immport_expsamp_acc: ImmPort:ES1167279', 'immport_expsamp_acc: ImmPort:ES1167280', 'immport_expsamp_acc: ImmPort:ES1167281', 'immport_expsamp_acc: ImmPort:ES1167282', 'immport_expsamp_acc: ImmPort:ES1167283', 'immport_expsamp_acc: ImmPort:ES1167284', 'immport_expsamp_acc: ImmPort:ES1167285', 'immport_expsamp_acc: ImmPort:ES1167286', 'immport_expsamp_acc: ImmPort:ES1167287', 'immport_expsamp_acc: ImmPort:ES1167288', 'immport_expsamp_acc: ImmPort:ES1167289', 'immport_expsamp_acc: ImmPort:ES1167290', 'immport_expsamp_acc: ImmPort:ES1167291', 'immport_expsamp_acc: ImmPort:ES1167292', 'immport_expsamp_acc: ImmPort:ES1167293', 'immport_expsamp_acc: ImmPort:ES1167294', 'immport_expsamp_acc: ImmPort:ES1167295', 'immport_expsamp_acc: ImmPort:ES1167296', 'immport_expsamp_acc: ImmPort:ES1167297', 'immport_expsamp_acc: ImmPort:ES1167298', 'immport_expsamp_acc: ImmPort:ES1167299', 'immport_expsamp_acc: ImmPort:ES1167300', 'immport_expsamp_acc: ImmPort:ES1167301', 'immport_expsamp_acc: ImmPort:ES1167302', 'immport_expsamp_acc: ImmPort:ES1167303']}\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": "f1de7f5c",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "0a3c1212",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T05:40:06.232312Z",
"iopub.status.busy": "2025-03-25T05:40:06.232192Z",
"iopub.status.idle": "2025-03-25T05:40:06.251046Z",
"shell.execute_reply": "2025-03-25T05:40:06.250758Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"A new JSON file was created at: ../../output/preprocess/Height/cohort_info.json\n"
]
},
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"# From background information, we see it contains gene expression data from human PBMC samples\n",
"# using \"Human HT12-V4.0 BeadChip\" - this is a gene expression microarray\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"# For height (our trait), we can see in the background info that height data was collected\n",
"# \"Each subject was evaluated by a screening questionnaire determining self-reported demographic information, height, weight...\"\n",
"# However, we don't see height data in the sample characteristics dictionary\n",
"trait_row = None # Height data not available in the sample characteristics\n",
"\n",
"# For age, the sample characteristics dictionary shows age group data at index 1\n",
"age_row = 1 # Age group data is available at index 1\n",
"\n",
"# Gender data is not explicitly available in the sample characteristics\n",
"gender_row = None # Gender data not available\n",
"\n",
"# 2.2 Data Type Conversion\n",
"# For height (not available, but define a function anyway)\n",
"def convert_trait(value):\n",
" if not value or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract the value after colon if it exists\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" try:\n",
" # Height would typically be a continuous value\n",
" return float(value)\n",
" except (ValueError, TypeError):\n",
" return None\n",
"\n",
"# For age (available as age group)\n",
"def convert_age(value):\n",
" if not value or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract the value after colon if it exists\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Convert age group to binary (Young=0, Older/Frail=1)\n",
" if 'young' in value.lower():\n",
" return 0\n",
" elif 'older' in value.lower() or 'frail' in value.lower():\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"# For gender (not available, but define a function anyway)\n",
"def convert_gender(value):\n",
" if not value or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract the value after colon if it exists\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Convert gender to binary (female=0, male=1)\n",
" if 'female' in value.lower() or 'f' == value.lower():\n",
" return 0\n",
" elif 'male' in value.lower() or 'm' == value.lower():\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# The trait data is not available (trait_row is None)\n",
"is_trait_available = trait_row is not None\n",
"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 - Skip as trait_row is None\n"
]
},
{
"cell_type": "markdown",
"id": "1d360dfe",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "a781107c",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T05:40:06.252196Z",
"iopub.status.busy": "2025-03-25T05:40:06.252086Z",
"iopub.status.idle": "2025-03-25T05:40:06.912356Z",
"shell.execute_reply": "2025-03-25T05:40:06.911956Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Extracting gene data from matrix file:\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Successfully extracted gene data with 46892 rows\n",
"First 20 gene IDs:\n",
"Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n",
" 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n",
" 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n",
" 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n",
" 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n",
" dtype='object', name='ID')\n",
"\n",
"Gene expression data available: True\n"
]
}
],
"source": [
"# 1. Get the file paths for the SOFT file and matrix file\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Extract gene expression data from the matrix file\n",
"try:\n",
" print(\"Extracting gene data from matrix file:\")\n",
" gene_data = get_genetic_data(matrix_file)\n",
" if gene_data.empty:\n",
" print(\"Extracted gene expression data is empty\")\n",
" is_gene_available = False\n",
" else:\n",
" print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n",
" print(\"First 20 gene IDs:\")\n",
" print(gene_data.index[:20])\n",
" is_gene_available = True\n",
"except Exception as e:\n",
" print(f\"Error extracting gene data: {e}\")\n",
" print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n",
" is_gene_available = False\n",
"\n",
"print(f\"\\nGene expression data available: {is_gene_available}\")\n"
]
},
{
"cell_type": "markdown",
"id": "1e48f28c",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "c27d7239",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T05:40:06.913760Z",
"iopub.status.busy": "2025-03-25T05:40:06.913643Z",
"iopub.status.idle": "2025-03-25T05:40:06.915557Z",
"shell.execute_reply": "2025-03-25T05:40:06.915248Z"
}
},
"outputs": [],
"source": [
"# Based on the gene identifiers observed, these are Illumina microarray probe IDs (ILMN_) \n",
"# rather than standard human gene symbols. They need to be mapped to gene symbols for proper analysis.\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "71709be7",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "f07d43c6",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T05:40:06.916803Z",
"iopub.status.busy": "2025-03-25T05:40:06.916694Z",
"iopub.status.idle": "2025-03-25T05:40:07.880629Z",
"shell.execute_reply": "2025-03-25T05:40:07.880278Z"
}
},
"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 = [email protected]\n",
"Line 5: ^SERIES = GSE101709\n",
"Line 6: !Series_title = Gene expression analysis of Influenza vaccine response in Young and Old - Year 4\n",
"Line 7: !Series_geo_accession = GSE101709\n",
"Line 8: !Series_status = Public on Jan 08 2020\n",
"Line 9: !Series_submission_date = Jul 20 2017\n",
"Line 10: !Series_last_update_date = Jul 25 2021\n",
"Line 11: !Series_pubmed_id = 32060136\n",
"Line 12: !Series_summary = We profiled gene expression from a stratified cohort of subjects to define influenza vaccine response in Young and Old\n",
"Line 13: !Series_overall_design = Differential gene expression by human PBMCs from Healthy Adults receiving Influenza Vaccination (Fluvirin, Novartis). Healthy adults (older >65, younger 21-30 years) were recruited at seasonal Influenza Vaccination clinics organized by Yale University Health Services during October to December of 2013 – 2014 seasons. With informed consent, healthy individuals were recruited as per a protocol approved by Human Investigations Committee of the Yale University School of Medicine. Each subject was evaluated by a screening questionnaire determining self-reported demographic information, height, weight, medications and comorbid conditions. Participants with acute illness two weeks prior to vaccination were excluded from study. Blood samples were collected into BD Vacutainer Sodium Heparin tube at four different time points, once prior to administration of vaccine and three time points after vaccination on days 2, 7 and 28. Peripheral Blood Mononuclear Cells (PBMC) were isolated from heparinized blood using Histopaque 1077 in gradient centrifugation. About 1.0x10^7 freshly isolated PBMC were lysed in Triso and immediately stored in -80C. Total RNA in aqueous phase of Trisol - Chloroform was isolated in an automated QiaCube instrument using miRNeasy according to manufacturer’s instructions. Integrity of RNA samples were assessed by Agilent 2100 BioAnalyser Samples were processed for cRNA generation using Illumina TotalPrep cRNA Amplification Kit and subsequently hybridized to Human HT12-V4.0 BeadChip at Yale Center for Genomic Analysis (YGCA).\n",
"Line 14: !Series_overall_design =\n",
"Line 15: !Series_overall_design = The current data set, together with GSE59654, GSE59635, GSE59743, and GSE101710, represents subsets of the same overall study\n",
"Line 16: !Series_type = Expression profiling by array\n",
"Line 17: !Series_contributor = Albert,C,Shaw\n",
"Line 18: !Series_contributor = Subhasis,,Mohanty\n",
"Line 19: !Series_contributor = Hailong,,Meng\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": "3c02687f",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "78300917",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T05:40:07.882045Z",
"iopub.status.busy": "2025-03-25T05:40:07.881913Z",
"iopub.status.idle": "2025-03-25T05:40:08.072767Z",
"shell.execute_reply": "2025-03-25T05:40:08.072398Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Created gene mapping with 44837 entries\n",
"Gene mapping preview:\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 probe-level data to gene-level expression data with 21344 genes\n",
"First few genes:\n",
"Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n",
" 'A4GALT', 'A4GNT'],\n",
" dtype='object', name='Gene')\n",
"Successfully mapped expression data to 21344 genes\n"
]
}
],
"source": [
"# 1. Determine which columns contain the probe IDs and gene symbols\n",
"# From the previous output, we can see:\n",
"# - 'ID' column contains the probe IDs (ILMN_*) that match our gene expression data\n",
"# - 'Symbol' column contains the gene symbols we need to map to\n",
"\n",
"# 2. Extract the gene mapping dataframe from the gene annotation\n",
"probe_id_col = 'ID'\n",
"gene_symbol_col = 'Symbol'\n",
"\n",
"# Create the mapping dataframe\n",
"gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n",
"print(f\"Created gene mapping with {len(gene_mapping)} entries\")\n",
"print(\"Gene mapping preview:\")\n",
"print(gene_mapping.head())\n",
"\n",
"# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
"gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
"print(f\"Converted probe-level data to gene-level expression data with {len(gene_data)} genes\")\n",
"print(\"First few genes:\")\n",
"print(gene_data.index[:10])\n",
"\n",
"# Check if we have successfully extracted genes\n",
"if gene_data.empty:\n",
" print(\"Warning: Mapped gene expression data is empty\")\n",
" is_gene_available = False\n",
"else:\n",
" print(f\"Successfully mapped expression data to {len(gene_data.index)} genes\")\n",
" is_gene_available = True\n"
]
},
{
"cell_type": "markdown",
"id": "90977699",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "4c6428d8",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T05:40:08.074052Z",
"iopub.status.busy": "2025-03-25T05:40:08.073931Z",
"iopub.status.idle": "2025-03-25T05:40:09.824683Z",
"shell.execute_reply": "2025-03-25T05:40:09.824296Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene data before normalization: (21344, 98)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene data after normalization: (20158, 98)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene expression data saved to ../../output/preprocess/Height/gene_data/GSE101709.csv\n",
"Added Age data to clinical dataframe\n",
"Clinical data saved to ../../output/preprocess/Height/clinical_data/GSE101709.csv\n",
"Linked data shape: (98, 20160)\n",
"Dataset usability: False\n",
"Dataset does not contain Height data and cannot be used for association studies.\n"
]
}
],
"source": [
"# 1. Normalize gene symbols in the gene expression data\n",
"import numpy as np\n",
"import os\n",
"\n",
"print(f\"Gene data before normalization: {gene_data.shape}\")\n",
"\n",
"try:\n",
" # Try to normalize gene symbols using the NCBI Gene database\n",
" normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
" print(f\"Gene data after normalization: {normalized_gene_data.shape}\")\n",
" \n",
" # If normalization resulted in empty dataframe, use the original gene data\n",
" if normalized_gene_data.empty:\n",
" print(\"Warning: Normalization resulted in empty gene data. Using original gene data instead.\")\n",
" normalized_gene_data = gene_data\n",
" \n",
"except Exception as e:\n",
" print(f\"Error during gene symbol normalization: {e}\")\n",
" print(\"Using original gene data instead.\")\n",
" normalized_gene_data = gene_data\n",
"\n",
"# Save gene expression 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\"Gene expression data saved to {out_gene_data_file}\")\n",
"\n",
"# 2. Create a minimal clinical dataframe since we don't have trait data\n",
"sample_ids = gene_data.columns\n",
"minimal_clinical_df = pd.DataFrame(index=sample_ids)\n",
"minimal_clinical_df[trait] = np.nan # Add the trait column with NaN values\n",
"\n",
"# If we have age data from Step 2, add that column\n",
"if age_row is not None:\n",
" try:\n",
" minimal_clinical_df['Age'] = get_feature_data(clinical_data, age_row, 'Age', convert_age).iloc[0]\n",
" print(\"Added Age data to clinical dataframe\")\n",
" except Exception as e:\n",
" print(f\"Error adding age data: {e}\")\n",
"\n",
"# If we have gender data from Step 2, add that column\n",
"if gender_row is not None:\n",
" try:\n",
" minimal_clinical_df['Gender'] = get_feature_data(clinical_data, gender_row, 'Gender', convert_gender).iloc[0]\n",
" print(\"Added Gender data to clinical dataframe\")\n",
" except Exception as e:\n",
" print(f\"Error adding gender data: {e}\")\n",
"\n",
"# Save clinical data\n",
"os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
"minimal_clinical_df.to_csv(out_clinical_data_file)\n",
"print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
"\n",
"# Link clinical and genetic data\n",
"try:\n",
" linked_data = pd.concat([minimal_clinical_df, normalized_gene_data.T], axis=1)\n",
" linked_data.index.name = 'Sample'\n",
" print(f\"Linked data shape: {linked_data.shape}\")\n",
"except Exception as e:\n",
" print(f\"Error linking clinical and genetic data: {e}\")\n",
" # Create a minimal dataframe with just the trait for validation\n",
" linked_data = minimal_clinical_df\n",
" print(f\"Using only clinical data with shape: {linked_data.shape}\")\n",
"\n",
"# Since trait_row was None in Step 2, we know Height data is not available\n",
"is_trait_available = False \n",
"\n",
"# Add a detailed note about the dataset limitations\n",
"note = \"Dataset contains gene expression data but no Height measurements. The dataset includes age group information (Young vs Older/Frail) but lacks the specific trait data needed for Height association studies.\"\n",
"\n",
"# For datasets without trait data, we set is_biased to False\n",
"is_biased = False\n",
"\n",
"# Final validation and data quality assessment\n",
"is_usable = validate_and_save_cohort_info(\n",
" is_final=True, \n",
" cohort=cohort, \n",
" info_path=json_path, \n",
" is_gene_available=is_gene_available, \n",
" is_trait_available=is_trait_available, \n",
" is_biased=is_biased,\n",
" df=linked_data,\n",
" note=note\n",
")\n",
"\n",
"# Only save the linked data if it's usable for our study\n",
"print(f\"Dataset usability: {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 does not contain Height data and cannot be used for 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
}
|