File size: 33,962 Bytes
92d2f89 |
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 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "f362c874",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:25:37.751686Z",
"iopub.status.busy": "2025-03-25T06:25:37.751507Z",
"iopub.status.idle": "2025-03-25T06:25:37.917224Z",
"shell.execute_reply": "2025-03-25T06:25:37.916829Z"
}
},
"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 = \"Alzheimers_Disease\"\n",
"cohort = \"GSE117589\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Alzheimers_Disease\"\n",
"in_cohort_dir = \"../../input/GEO/Alzheimers_Disease/GSE117589\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Alzheimers_Disease/GSE117589.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Alzheimers_Disease/gene_data/GSE117589.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Alzheimers_Disease/clinical_data/GSE117589.csv\"\n",
"json_path = \"../../output/preprocess/Alzheimers_Disease/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "c35049cb",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "f4aad409",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:25:37.918737Z",
"iopub.status.busy": "2025-03-25T06:25:37.918589Z",
"iopub.status.idle": "2025-03-25T06:25:38.009147Z",
"shell.execute_reply": "2025-03-25T06:25:38.008804Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"REST and Neural Gene Network Dysregulation in iPS Cell Models of Alzheimer’s Disease\"\n",
"!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
"!Series_overall_design\t\"Refer to individual Series\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['cell type: induced pluripotent stem cells', 'cell type: neurons', 'cell type: neural progenitor cells'], 1: ['subject: 60F', 'subject: 64M', 'subject: 72M', 'subject: 73M', 'subject: 75F', 'subject: 92F', 'subject: 60M', 'subject: 69F', 'subject: 87F'], 2: ['diagnosis: normal', \"diagnosis: sporadic Alzheimer's disease\"], 3: ['clone: Clone 1', 'clone: Clone 2'], 4: ['coriell #: AG04455', 'coriell #: AG08125', 'coriell #: AG08379', 'coriell #: AG08509', 'coriell #: AG14244', 'coriell #: AG09173', 'coriell #: AG07376', 'coriell #: AG21158', 'coriell #: AG08243', 'coriell #: AG10788', 'coriell #: AG06869']}\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": "1c037745",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "1d67ad1b",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:25:38.010196Z",
"iopub.status.busy": "2025-03-25T06:25:38.010078Z",
"iopub.status.idle": "2025-03-25T06:25:38.031828Z",
"shell.execute_reply": "2025-03-25T06:25:38.031496Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Preview of extracted clinical features:\n",
"{'GSM3304268': [0.0, 60.0, 0.0], 'GSM3304269': [0.0, 64.0, 1.0], 'GSM3304270': [0.0, 72.0, 1.0], 'GSM3304271': [0.0, 73.0, 1.0], 'GSM3304272': [0.0, 75.0, 0.0], 'GSM3304273': [0.0, 92.0, 0.0], 'GSM3304274': [1.0, 60.0, 1.0], 'GSM3304275': [1.0, 69.0, 0.0], 'GSM3304276': [1.0, 72.0, 1.0], 'GSM3304277': [1.0, 87.0, 0.0], 'GSM3304278': [0.0, 60.0, 0.0], 'GSM3304279': [0.0, 64.0, 1.0], 'GSM3304280': [0.0, 72.0, 1.0], 'GSM3304281': [0.0, 73.0, 1.0], 'GSM3304282': [0.0, 75.0, 0.0], 'GSM3304283': [0.0, 92.0, 0.0], 'GSM3304284': [1.0, 60.0, 0.0], 'GSM3304285': [1.0, 60.0, 1.0], 'GSM3304286': [1.0, 69.0, 0.0], 'GSM3304287': [1.0, 72.0, 1.0], 'GSM3304288': [1.0, 87.0, 0.0], 'GSM3304289': [0.0, 60.0, 0.0], 'GSM3304290': [0.0, 64.0, 1.0], 'GSM3304291': [0.0, 72.0, 1.0], 'GSM3304292': [0.0, 73.0, 1.0], 'GSM3304293': [0.0, 92.0, 0.0], 'GSM3304294': [1.0, 60.0, 0.0], 'GSM3304295': [1.0, 60.0, 1.0], 'GSM3304296': [1.0, 69.0, 0.0], 'GSM3304297': [1.0, 72.0, 1.0], 'GSM3304298': [1.0, 87.0, 0.0]}\n",
"Clinical features saved to ../../output/preprocess/Alzheimers_Disease/clinical_data/GSE117589.csv\n"
]
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"# Based on the background information and sample characteristics, this appears to be a dataset with gene expression data\n",
"# from iPSCs, neurons, and neural progenitor cells. Therefore, gene expression data is likely available.\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"\n",
"# For Alzheimer's Disease trait:\n",
"# Looking at key 2, we see \"diagnosis: normal\" and \"diagnosis: sporadic Alzheimer's disease\"\n",
"trait_row = 2\n",
"\n",
"# For age:\n",
"# Age is not explicitly given but might be inferred from key 1 where subject info contains age and gender\n",
"# e.g., 'subject: 60F', 'subject: 64M'\n",
"age_row = 1\n",
"\n",
"# For gender:\n",
"# Gender is also in key 1 as part of subject information\n",
"gender_row = 1\n",
"\n",
"# 2.2 Data Type Conversion\n",
"\n",
"def convert_trait(value):\n",
" if not isinstance(value, str):\n",
" return None\n",
" value = value.split(': ')[-1].strip().lower()\n",
" if \"alzheimer\" in value or \"ad\" in value:\n",
" return 1\n",
" elif \"normal\" in value or \"control\" in value or \"healthy\" in value:\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" if not isinstance(value, str):\n",
" return None\n",
" # Extract age from patterns like 'subject: 60F', 'subject: 64M'\n",
" value = value.split(': ')[-1].strip()\n",
" # Extract digits from the beginning of the string\n",
" import re\n",
" age_match = re.match(r'^(\\d+)', value)\n",
" if age_match:\n",
" try:\n",
" return int(age_match.group(1))\n",
" except ValueError:\n",
" return None\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" if not isinstance(value, str):\n",
" return None\n",
" # Extract gender from patterns like 'subject: 60F', 'subject: 64M'\n",
" value = value.split(': ')[-1].strip()\n",
" # Check if the last character is 'F' or 'M'\n",
" if value.endswith('F'):\n",
" return 0 # Female\n",
" elif value.endswith('M'):\n",
" return 1 # Male\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Determine if trait data is available\n",
"is_trait_available = trait_row is not None\n",
"validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n",
" is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n",
"\n",
"# 4. Clinical Feature Extraction\n",
"if trait_row is not None:\n",
" # Assume clinical_data is already loaded from a previous step\n",
" try:\n",
" # Extract clinical features using the clinical_data DataFrame from step 1\n",
" clinical_features = 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 extracted clinical features\n",
" print(\"Preview of extracted clinical features:\")\n",
" print(preview_df(clinical_features))\n",
" \n",
" # Save the extracted clinical features\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" clinical_features.to_csv(out_clinical_data_file, index=False)\n",
" print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
" except NameError:\n",
" print(\"Clinical data not available from previous steps. Skipping clinical feature extraction.\")\n",
" except Exception as e:\n",
" print(f\"Error in clinical feature extraction: {e}\")\n"
]
},
{
"cell_type": "markdown",
"id": "eede0869",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "ace4ccca",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:25:38.032917Z",
"iopub.status.busy": "2025-03-25T06:25:38.032804Z",
"iopub.status.idle": "2025-03-25T06:25:38.116296Z",
"shell.execute_reply": "2025-03-25T06:25:38.115929Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"First 20 gene/probe identifiers:\n",
"Index(['ENSG00000000003_at', 'ENSG00000000005_at', 'ENSG00000000419_at',\n",
" 'ENSG00000000457_at', 'ENSG00000000460_at', 'ENSG00000000938_at',\n",
" 'ENSG00000000971_at', 'ENSG00000001036_at', 'ENSG00000001084_at',\n",
" 'ENSG00000001167_at', 'ENSG00000001460_at', 'ENSG00000001461_at',\n",
" 'ENSG00000001497_at', 'ENSG00000001561_at', 'ENSG00000001617_at',\n",
" 'ENSG00000001626_at', 'ENSG00000001629_at', 'ENSG00000001631_at',\n",
" 'ENSG00000002016_at', 'ENSG00000002079_at'],\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": "99156441",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "98f0cc09",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:25:38.117690Z",
"iopub.status.busy": "2025-03-25T06:25:38.117568Z",
"iopub.status.idle": "2025-03-25T06:25:38.119538Z",
"shell.execute_reply": "2025-03-25T06:25:38.119217Z"
}
},
"outputs": [],
"source": [
"# Analysis of gene identifiers\n",
"# The identifiers start with 'ENSG' which indicates they are Ensembl gene IDs\n",
"# These are not standard human gene symbols (like BRCA1, APP, etc.)\n",
"# Ensembl IDs need to be mapped to standard gene symbols for better interpretability\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "27223c64",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "767604d2",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:25:38.120814Z",
"iopub.status.busy": "2025-03-25T06:25:38.120700Z",
"iopub.status.idle": "2025-03-25T06:25:38.865986Z",
"shell.execute_reply": "2025-03-25T06:25:38.865603Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene annotation preview:\n",
"{'ID': ['ENSG00000000003_at', 'ENSG00000000005_at', 'ENSG00000000419_at', 'ENSG00000000457_at', 'ENSG00000000460_at'], 'SPOT_ID': ['ENSG00000000003', 'ENSG00000000005', 'ENSG00000000419', 'ENSG00000000457', 'ENSG00000000460'], 'Description': ['tetraspanin 6 [Source:HGNC Symbol;Acc:HGNC:11858]', 'tenomodulin [Source:HGNC Symbol;Acc:HGNC:17757]', 'dolichyl-phosphate mannosyltransferase subunit 1, catalytic [Source:HGNC Symbol;Acc:HGNC:3005]', 'SCY1 like pseudokinase 3 [Source:HGNC Symbol;Acc:HGNC:19285]', 'chromosome 1 open reading frame 112 [Source:HGNC Symbol;Acc:HGNC:25565]']}\n"
]
}
],
"source": [
"# 1. First get the file paths using geo_get_relevant_filepaths function\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
"gene_annotation = get_gene_annotation(soft_file)\n",
"\n",
"# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
"print(\"Gene annotation preview:\")\n",
"print(preview_df(gene_annotation))\n"
]
},
{
"cell_type": "markdown",
"id": "60f1a9f6",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "fdc3d9f0",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:25:38.867417Z",
"iopub.status.busy": "2025-03-25T06:25:38.867286Z",
"iopub.status.idle": "2025-03-25T06:25:39.342695Z",
"shell.execute_reply": "2025-03-25T06:25:39.342322Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Sample SPOT_ID and Description pairs:\n",
"SPOT_ID: ENSG00000000003 - Description: tetraspanin 6 [Source:HGNC Symbol;Acc:HGNC:11858]\n",
"SPOT_ID: ENSG00000000005 - Description: tenomodulin [Source:HGNC Symbol;Acc:HGNC:17757]\n",
"SPOT_ID: ENSG00000000419 - Description: dolichyl-phosphate mannosyltransferase subunit 1, catalytic [Source:HGNC Symbol;Acc:HGNC:3005]\n",
"SPOT_ID: ENSG00000000457 - Description: SCY1 like pseudokinase 3 [Source:HGNC Symbol;Acc:HGNC:19285]\n",
"SPOT_ID: ENSG00000000460 - Description: chromosome 1 open reading frame 112 [Source:HGNC Symbol;Acc:HGNC:25565]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene mapping preview:\n",
"{'ID': ['ENSG00000000003_at', 'ENSG00000000005_at', 'ENSG00000000419_at', 'ENSG00000000457_at', 'ENSG00000000460_at'], 'Gene': [['HGNC'], ['HGNC'], ['HGNC'], ['SCY1', 'HGNC'], ['HGNC']]}\n",
"Number of probes with gene symbols: 18144\n",
"Gene data shape before normalization: (0, 31)\n",
"Sample gene symbols before normalization:\n",
"[]\n",
"Gene data shape after normalization: (0, 31)\n",
"\n",
"Processed gene expression data preview (first 5 rows, 5 columns):\n",
"Gene data is empty after processing\n",
"Processed gene data saved to ../../output/preprocess/Alzheimers_Disease/gene_data/GSE117589.csv\n"
]
}
],
"source": [
"# 1. Determine which columns contain gene identifiers and gene symbols\n",
"# The 'ID' column in gene_annotation matches the index in gene_data\n",
"# We need to extract the official gene symbols from the Description field\n",
"\n",
"# Let's look at the SPOT_ID and Description columns more closely\n",
"print(\"Sample SPOT_ID and Description pairs:\")\n",
"for i in range(min(5, len(gene_annotation))):\n",
" print(f\"SPOT_ID: {gene_annotation.iloc[i]['SPOT_ID']} - Description: {gene_annotation.iloc[i]['Description']}\")\n",
"\n",
"# Create a mapping from ENSEMBL IDs to gene symbols using regex to extract symbols from Description\n",
"import re\n",
"\n",
"def extract_gene_symbol_from_description(description_text):\n",
" if not isinstance(description_text, str):\n",
" return []\n",
" \n",
" # Pattern to extract HGNC symbols from description\n",
" # Example: \"tetraspanin 6 [Source:HGNC Symbol;Acc:HGNC:11858]\" -> extract the HGNC ID 11858\n",
" hgnc_match = re.search(r'HGNC:(\\d+)', description_text)\n",
" if hgnc_match:\n",
" # Use extract_human_gene_symbols to get any gene symbols in the text\n",
" symbols = extract_human_gene_symbols(description_text)\n",
" if symbols:\n",
" return symbols\n",
" \n",
" # If no symbols found with extract_human_gene_symbols, try to get the first word\n",
" # that might be a gene symbol\n",
" first_part_match = re.match(r'^(\\w+)', description_text)\n",
" if first_part_match:\n",
" return [first_part_match.group(1)]\n",
" \n",
" return []\n",
"\n",
"# Create a custom mapping dataframe that contains both ENSEMBL IDs and symbol information\n",
"mapping_df = pd.DataFrame({\n",
" 'ID': gene_annotation['ID'],\n",
" 'Gene': gene_annotation['Description'].apply(extract_human_gene_symbols)\n",
"})\n",
"\n",
"# Filter out rows where Gene is an empty list\n",
"mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
"\n",
"# Print the first few rows of the mapping to verify\n",
"print(\"Gene mapping preview:\")\n",
"print(preview_df(mapping_df))\n",
"print(f\"Number of probes with gene symbols: {len(mapping_df)}\")\n",
"\n",
"# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
"gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
"\n",
"# Print shape before normalization\n",
"print(f\"Gene data shape before normalization: {gene_data.shape}\")\n",
"\n",
"# Check if gene symbols need normalization\n",
"print(\"Sample gene symbols before normalization:\")\n",
"print(list(gene_data.index[:10]))\n",
"\n",
"# Normalize gene symbols to ensure consistency\n",
"gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"\n",
"# Print shape after normalization\n",
"print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
"\n",
"# Preview the first few rows of the processed gene expression data\n",
"print(\"\\nProcessed gene expression data preview (first 5 rows, 5 columns):\")\n",
"if not gene_data.empty:\n",
" print(gene_data.iloc[:5, :5])\n",
"else:\n",
" print(\"Gene data is empty after processing\")\n",
"\n",
"# Save the processed gene data to file\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"gene_data.to_csv(out_gene_data_file)\n",
"print(f\"Processed gene data saved to {out_gene_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "a1524db6",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "972390aa",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:25:39.344195Z",
"iopub.status.busy": "2025-03-25T06:25:39.344071Z",
"iopub.status.idle": "2025-03-25T06:25:40.736480Z",
"shell.execute_reply": "2025-03-25T06:25:40.736105Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene mapping preview:\n",
"{'ID': ['ENSG00000000003_at', 'ENSG00000000005_at', 'ENSG00000000419_at', 'ENSG00000000457_at', 'ENSG00000000460_at'], 'Gene': [['HGNC'], ['HGNC'], ['HGNC'], ['SCY1', 'HGNC'], ['HGNC']]}\n",
"Number of probes with gene symbols: 18145\n",
"\n",
"Gene expression data preview:\n",
"Gene expression data shape: (0, 31)\n",
"Sample column names: ['GSM3304268', 'GSM3304269', 'GSM3304270', 'GSM3304271', 'GSM3304272']\n",
"Re-loaded gene data shape: (20027, 31)\n",
"Gene data shape after mapping: (0, 31)\n",
"Mapped gene data is suspiciously small. Trying alternative approach...\n",
"Alternative mapping created with 18146 entries\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene data shape after alternative mapping: (2551, 31)\n",
"Processed gene data saved to ../../output/preprocess/Alzheimers_Disease/gene_data/GSE117589.csv\n"
]
}
],
"source": [
"# 1. First get the file paths using geo_get_relevant_filepaths function\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
"gene_annotation = get_gene_annotation(soft_file)\n",
"\n",
"# 3. Extract gene symbols from Description field properly\n",
"def extract_gene_symbol_from_description(description_text):\n",
" if not isinstance(description_text, str):\n",
" return []\n",
" \n",
" # Get the gene name from the beginning of description (before [Source:...])\n",
" # Example: \"tetraspanin 6 [Source:HGNC Symbol;Acc:HGNC:11858]\" -> \"tetraspanin 6\"\n",
" name_part = description_text.split('[Source:')[0].strip()\n",
" \n",
" # Many descriptions have format \"Gene Name [Source:...]\" - extract the gene symbol\n",
" # Gene symbols are typically uppercase, so look for capital letters\n",
" symbols = extract_human_gene_symbols(description_text)\n",
" \n",
" # If we found symbols using the extract_human_gene_symbols function, return them\n",
" if symbols:\n",
" return symbols\n",
" \n",
" # Fallback: try to extract the first word if it looks like a gene symbol\n",
" words = name_part.split()\n",
" if words and len(words[0]) <= 10 and any(c.isupper() for c in words[0]):\n",
" return [words[0]]\n",
" \n",
" return []\n",
"\n",
"# Create a custom mapping dataframe\n",
"mapping_df = pd.DataFrame({\n",
" 'ID': gene_annotation['ID'],\n",
" 'Gene': gene_annotation['Description'].apply(extract_gene_symbol_from_description)\n",
"})\n",
"\n",
"# Filter out rows where Gene is an empty list\n",
"mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n",
"\n",
"# Print the first few rows of the mapping to verify\n",
"print(\"Gene mapping preview:\")\n",
"print(preview_df(mapping_df))\n",
"print(f\"Number of probes with gene symbols: {len(mapping_df)}\")\n",
"\n",
"# Let's also check gene expression data to make sure it's not empty\n",
"print(\"\\nGene expression data preview:\")\n",
"print(f\"Gene expression data shape: {gene_data.shape}\")\n",
"print(f\"Sample column names: {list(gene_data.columns[:5])}\")\n",
"\n",
"# Extract gene expression data again from the matrix file to ensure we have good data\n",
"gene_data = get_genetic_data(matrix_file)\n",
"print(f\"Re-loaded gene data shape: {gene_data.shape}\")\n",
"\n",
"# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
"gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n",
"print(f\"Gene data shape after mapping: {gene_data_mapped.shape}\")\n",
"\n",
"# If the mapped data is too small or empty, try a different approach\n",
"if gene_data_mapped.shape[0] < 100:\n",
" print(\"Mapped gene data is suspiciously small. Trying alternative approach...\")\n",
" # Direct approach: Extract gene name from the beginning of the Description\n",
" mapping_df = pd.DataFrame({\n",
" 'ID': gene_annotation['ID'],\n",
" 'Gene': gene_annotation['Description'].apply(lambda x: \n",
" x.split('[')[0].strip() if isinstance(x, str) else '')\n",
" })\n",
" # Keep only non-empty gene names\n",
" mapping_df = mapping_df[mapping_df['Gene'] != '']\n",
" print(f\"Alternative mapping created with {len(mapping_df)} entries\")\n",
" \n",
" # Apply alternative mapping\n",
" gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n",
" print(f\"Gene data shape after alternative mapping: {gene_data_mapped.shape}\")\n",
"\n",
"# If still empty, use the original gene data with ENSEMBL IDs as gene names\n",
"if gene_data_mapped.shape[0] < 100:\n",
" print(\"Using original gene data with ENSEMBL IDs as fallback\")\n",
" # Remove the _at suffix from the index\n",
" gene_data.index = gene_data.index.str.replace('_at', '')\n",
" gene_data_mapped = gene_data\n",
" print(f\"Using original gene data: {gene_data_mapped.shape}\")\n",
"\n",
"# Save the processed gene data to file\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"gene_data_mapped.to_csv(out_gene_data_file)\n",
"print(f\"Processed gene data saved to {out_gene_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "af163808",
"metadata": {},
"source": [
"### Step 8: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "740e6730",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T06:25:40.737991Z",
"iopub.status.busy": "2025-03-25T06:25:40.737869Z",
"iopub.status.idle": "2025-03-25T06:25:40.757971Z",
"shell.execute_reply": "2025-03-25T06:25:40.757644Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Clinical data columns: Index(['GSM3304268', 'GSM3304269', 'GSM3304270', 'GSM3304271', 'GSM3304272',\n",
" 'GSM3304273', 'GSM3304274', 'GSM3304275', 'GSM3304276', 'GSM3304277',\n",
" 'GSM3304278', 'GSM3304279', 'GSM3304280', 'GSM3304281', 'GSM3304282',\n",
" 'GSM3304283', 'GSM3304284', 'GSM3304285', 'GSM3304286', 'GSM3304287',\n",
" 'GSM3304288', 'GSM3304289', 'GSM3304290', 'GSM3304291', 'GSM3304292',\n",
" 'GSM3304293', 'GSM3304294', 'GSM3304295', 'GSM3304296', 'GSM3304297',\n",
" 'GSM3304298'],\n",
" dtype='object')\n",
"Gene data shape: (2551, 31)\n",
"Linked data shape: (2554, 31)\n",
"Linked data index preview: ['Alzheimers_Disease', 'Age', 'Gender', 'A-', 'A-52', 'A0', 'A1', 'A10', 'A11', 'A12']\n",
"Transposed linked data shape: (31, 2554)\n",
"Actual columns in linked_data: ['Alzheimers_Disease', 'Age', 'Gender', 'A-', 'A-52', 'A0', 'A1', 'A10', 'A11', 'A12']\n",
"Data shape after handling missing values: (0, 2)\n",
"Quartiles for 'Alzheimers_Disease':\n",
" 25%: nan\n",
" 50% (Median): nan\n",
" 75%: nan\n",
"Min: nan\n",
"Max: nan\n",
"The distribution of the feature 'Alzheimers_Disease' in this dataset is fine.\n",
"\n",
"Quartiles for 'Age':\n",
" 25%: nan\n",
" 50% (Median): nan\n",
" 75%: nan\n",
"Min: nan\n",
"Max: nan\n",
"The distribution of the feature 'Age' in this dataset is fine.\n",
"\n",
"Trait bias assessment: False\n",
"Data columns after bias assessment: ['Alzheimers_Disease', 'Age']\n",
"Abnormality detected in the cohort: GSE117589. Preprocessing failed.\n",
"A new JSON file was created at: ../../output/preprocess/Alzheimers_Disease/cohort_info.json\n",
"Dataset not usable due to bias or other issues. Linked data not saved.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_51556/2649569560.py:40: FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.\n",
" linked_data = pd.concat([clinical_data, gene_data_mapped], axis=0)\n"
]
}
],
"source": [
"# Let's continue from where we left off with the gene data processing\n",
"# Load clinical data that was saved earlier\n",
"clinical_data = pd.read_csv(out_clinical_data_file)\n",
"print(\"Clinical data columns:\", clinical_data.columns)\n",
"\n",
"# Load gene expression data \n",
"gene_data_mapped = pd.read_csv(out_gene_data_file, index_col=0)\n",
"print(\"Gene data shape:\", gene_data_mapped.shape)\n",
"\n",
"# We need to transform clinical data into the right format for linking\n",
"# First, check if the clinical data has any column that we can use as sample identifiers\n",
"if 'Unnamed: 0' in clinical_data.columns:\n",
" clinical_data.rename(columns={'Unnamed: 0': 'Sample'}, inplace=True)\n",
" clinical_data.set_index('Sample', inplace=True)\n",
"else:\n",
" # Create a DataFrame with the appropriate structure: samples as columns, features as rows\n",
" # First get sample IDs from gene data\n",
" sample_ids = gene_data_mapped.columns.tolist()\n",
" \n",
" # Create a new DataFrame with the right structure\n",
" new_clinical_df = pd.DataFrame(index=[trait, 'Age', 'Gender'], columns=sample_ids)\n",
" \n",
" # Fill in the values - assuming clinical_data has the same order of samples\n",
" if len(clinical_data) == len(sample_ids):\n",
" for i, sample_id in enumerate(sample_ids):\n",
" if i < len(clinical_data):\n",
" # Get values from clinical_data row i\n",
" row = clinical_data.iloc[i]\n",
" # Assign values to the new DataFrame\n",
" if trait in row:\n",
" new_clinical_df.loc[trait, sample_id] = row[trait]\n",
" if 'Age' in row:\n",
" new_clinical_df.loc['Age', sample_id] = row['Age']\n",
" if 'Gender' in row:\n",
" new_clinical_df.loc['Gender', sample_id] = row['Gender']\n",
" \n",
" clinical_data = new_clinical_df\n",
"\n",
"# 2. Link clinical and genetic data\n",
"linked_data = pd.concat([clinical_data, gene_data_mapped], axis=0)\n",
"print(\"Linked data shape:\", linked_data.shape)\n",
"print(\"Linked data index preview:\", list(linked_data.index[:10]))\n",
"\n",
"# Transpose the linked data to have samples as rows and features as columns\n",
"linked_data = linked_data.T\n",
"print(\"Transposed linked data shape:\", linked_data.shape)\n",
"print(\"Actual columns in linked_data:\", linked_data.columns.tolist()[:10])\n",
"\n",
"# 3. Handle missing values - use the trait variable from environment setup\n",
"linked_data = handle_missing_values(linked_data, trait)\n",
"print(\"Data shape after handling missing values:\", linked_data.shape)\n",
"\n",
"# 4. Determine trait and demographic bias\n",
"is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
"print(f\"Trait bias assessment: {is_biased}\")\n",
"print(\"Data columns after bias assessment:\", list(linked_data.columns[:10]))\n",
"\n",
"# 5. Final quality validation and saving metadata\n",
"note = \"Used alternative gene mapping approach to extract gene symbols from descriptions.\"\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=True,\n",
" is_biased=is_biased,\n",
" df=linked_data,\n",
" note=note\n",
")\n",
"\n",
"# 6. Save linked data if 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, index=True)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
"else:\n",
" print(\"Dataset not usable due to bias or other issues. Linked data not saved.\")"
]
}
],
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.16"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|