File size: 41,163 Bytes
82732bd |
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 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "a9b8852e",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:57:31.196829Z",
"iopub.status.busy": "2025-03-25T03:57:31.196662Z",
"iopub.status.idle": "2025-03-25T03:57:31.359228Z",
"shell.execute_reply": "2025-03-25T03:57:31.358782Z"
}
},
"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 = \"Sickle_Cell_Anemia\"\n",
"cohort = \"GSE84634\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Sickle_Cell_Anemia\"\n",
"in_cohort_dir = \"../../input/GEO/Sickle_Cell_Anemia/GSE84634\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Sickle_Cell_Anemia/GSE84634.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Sickle_Cell_Anemia/gene_data/GSE84634.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Sickle_Cell_Anemia/clinical_data/GSE84634.csv\"\n",
"json_path = \"../../output/preprocess/Sickle_Cell_Anemia/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "5cdeb923",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "f39293de",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:57:31.360720Z",
"iopub.status.busy": "2025-03-25T03:57:31.360575Z",
"iopub.status.idle": "2025-03-25T03:57:31.439194Z",
"shell.execute_reply": "2025-03-25T03:57:31.438751Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"Gene expression of peripheral blood mononuclear cells from adults with sickle cell disease (University of Chicago cohort)\"\n",
"!Series_summary\t\"Sickle cell disease is associated with systemic complications, many associated with either severity of disease or increased risk of mortality. We sought to identify a circulating gene expression profile whose predictive capacity spanned the spectrum of these poor outcomes in sickle cell disease.\"\n",
"!Series_summary\t\"The Training cohort consisted of patients with SCD who were prospectively recruited from the University of Illinois. The Testing cohort consisted of a combination of patients prospectively seen at two separate institutions including the University of Chicago and Howard University.\"\n",
"!Series_overall_design\t\"The gene expression of PBMC from 38 sickle cell disease patients from University of Chicago were analyzed.\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['tissue: peripheral blood'], 1: ['cell type: mononuclear cells'], 2: ['disease: sickle cell disease']}\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": "650cdcdc",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "0eb82aff",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:57:31.440565Z",
"iopub.status.busy": "2025-03-25T03:57:31.440459Z",
"iopub.status.idle": "2025-03-25T03:57:31.447437Z",
"shell.execute_reply": "2025-03-25T03:57:31.446985Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Preview of clinical data:\n",
"{'characteristics_ch1': [1.0]}\n",
"Clinical data saved to ../../output/preprocess/Sickle_Cell_Anemia/clinical_data/GSE84634.csv\n"
]
}
],
"source": [
"import os\n",
"import json\n",
"import pandas as pd\n",
"from typing import Dict, Any, Callable, Optional\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this dataset contains gene expression data from PBMCs\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"# From sample characteristics, we can see \"disease: sickle cell disease\" corresponds to our trait\n",
"trait_row = 2 # \"disease: sickle cell disease\"\n",
"age_row = None # Age is not available in the sample characteristics\n",
"gender_row = None # Gender is not available in the sample characteristics\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"def convert_trait(value):\n",
" \"\"\"Convert trait value to binary format (0 = control, 1 = case).\"\"\"\n",
" if value is None:\n",
" return None\n",
" # Extract value after colon if present\n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" # From the data, everyone has sickle cell disease\n",
" # So this is a constant feature with all 1s\n",
" if \"sickle cell disease\" in value.lower():\n",
" return 1\n",
" else:\n",
" return None # For any unexpected values\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age value to continuous format.\"\"\"\n",
" # Not used as age data is not available\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender value to binary format (0 = female, 1 = male).\"\"\"\n",
" # Not used as gender data is not available\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Since trait_row is not None, trait data is available\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Validate and save cohort info (initial filtering)\n",
"validate_and_save_cohort_info(\n",
" is_final=False,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=is_gene_available,\n",
" is_trait_available=is_trait_available\n",
")\n",
"\n",
"# 4. Clinical Feature Extraction\n",
"# Since trait_row is not None, clinical data is available\n",
"if trait_row is not None:\n",
" # Assume clinical_data is already loaded from a previous step\n",
" clinical_data = pd.DataFrame({\"characteristics_ch1\": [\"disease: sickle cell disease\"] * 38}) # Based on the description of 38 SCD patients\n",
" \n",
" # Extract clinical features\n",
" selected_clinical_df = geo_select_clinical_features(\n",
" clinical_df=clinical_data,\n",
" trait=trait,\n",
" trait_row=trait_row,\n",
" convert_trait=convert_trait,\n",
" age_row=age_row,\n",
" convert_age=convert_age,\n",
" gender_row=gender_row,\n",
" convert_gender=convert_gender\n",
" )\n",
" \n",
" # Preview the dataframe\n",
" preview = preview_df(selected_clinical_df)\n",
" print(\"Preview of clinical data:\")\n",
" print(preview)\n",
" \n",
" # Create directory if it doesn't exist\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" \n",
" # Save to CSV\n",
" selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
" print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "ffa4f7c2",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "a913ec6d",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:57:31.448783Z",
"iopub.status.busy": "2025-03-25T03:57:31.448678Z",
"iopub.status.idle": "2025-03-25T03:57:31.548656Z",
"shell.execute_reply": "2025-03-25T03:57:31.548144Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found data marker at line 65\n",
"Header line: \"ID_REF\"\t\"GSM2243346\"\t\"GSM2243347\"\t\"GSM2243348\"\t\"GSM2243349\"\t\"GSM2243350\"\t\"GSM2243351\"\t\"GSM2243352\"\t\"GSM2243353\"\t\"GSM2243354\"\t\"GSM2243355\"\t\"GSM2243356\"\t\"GSM2243357\"\t\"GSM2243358\"\t\"GSM2243359\"\t\"GSM2243360\"\t\"GSM2243361\"\t\"GSM2243362\"\t\"GSM2243363\"\t\"GSM2243364\"\t\"GSM2243365\"\t\"GSM2243366\"\t\"GSM2243367\"\t\"GSM2243368\"\t\"GSM2243369\"\t\"GSM2243370\"\t\"GSM2243371\"\t\"GSM2243372\"\t\"GSM2243373\"\t\"GSM2243374\"\t\"GSM2243375\"\t\"GSM2243376\"\t\"GSM2243377\"\t\"GSM2243378\"\t\"GSM2243379\"\t\"GSM2243380\"\t\"GSM2243381\"\t\"GSM2243382\"\t\"GSM2243383\"\n",
"First data line: 2315554\t6.087148013\t6.505591352\t5.921904717\t6.15941806\t6.138992908\t6.032789074\t6.625662972\t6.089488274\t6.240933297\t6.014541988\t6.426659671\t6.494851638\t6.218330081\t6.189424379\t6.351294575\t6.507638473\t5.986528622\t6.190491525\t6.075310436\t6.304058565\t6.304614819\t6.753211011\t6.097934478\t6.23269389\t6.098436019\t6.311435772\t6.188093249\t5.776282784\t5.939137591\t6.056735194\t6.32142099\t6.341911205\t6.161502475\t6.343962963\t6.54086782\t6.221432023\t6.303210505\t6.090967623\n",
"Index(['2315554', '2315633', '2315674', '2315739', '2315894', '2315918',\n",
" '2315951', '2316218', '2316245', '2316379', '2316558', '2316605',\n",
" '2316746', '2316905', '2316953', '2317246', '2317317', '2317434',\n",
" '2317472', '2317512'],\n",
" dtype='object', name='ID')\n"
]
}
],
"source": [
"# 1. Get the file paths for the SOFT file and matrix file\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. First, let's examine the structure of the matrix file to understand its format\n",
"import gzip\n",
"\n",
"# Peek at the first few lines of the file to understand its structure\n",
"with gzip.open(matrix_file, 'rt') as file:\n",
" # Read first 100 lines to find the header structure\n",
" for i, line in enumerate(file):\n",
" if '!series_matrix_table_begin' in line:\n",
" print(f\"Found data marker at line {i}\")\n",
" # Read the next line which should be the header\n",
" header_line = next(file)\n",
" print(f\"Header line: {header_line.strip()}\")\n",
" # And the first data line\n",
" first_data_line = next(file)\n",
" print(f\"First data line: {first_data_line.strip()}\")\n",
" break\n",
" if i > 100: # Limit search to first 100 lines\n",
" print(\"Matrix table marker not found in first 100 lines\")\n",
" break\n",
"\n",
"# 3. Now try to get the genetic data with better error handling\n",
"try:\n",
" gene_data = get_genetic_data(matrix_file)\n",
" print(gene_data.index[:20])\n",
"except KeyError as e:\n",
" print(f\"KeyError: {e}\")\n",
" \n",
" # Alternative approach: manually extract the data\n",
" print(\"\\nTrying alternative approach to read the gene data:\")\n",
" with gzip.open(matrix_file, 'rt') as file:\n",
" # Find the start of the data\n",
" for line in file:\n",
" if '!series_matrix_table_begin' in line:\n",
" break\n",
" \n",
" # Read the headers and data\n",
" import pandas as pd\n",
" df = pd.read_csv(file, sep='\\t', index_col=0)\n",
" print(f\"Column names: {df.columns[:5]}\")\n",
" print(f\"First 20 row IDs: {df.index[:20]}\")\n",
" gene_data = df\n"
]
},
{
"cell_type": "markdown",
"id": "c0e1efb8",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "300b9845",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:57:31.550125Z",
"iopub.status.busy": "2025-03-25T03:57:31.550014Z",
"iopub.status.idle": "2025-03-25T03:57:31.552374Z",
"shell.execute_reply": "2025-03-25T03:57:31.551956Z"
}
},
"outputs": [],
"source": [
"# Examine the gene identifiers from the previous output\n",
"# The identifiers shown (2315554, 2315633, etc.) appear to be numeric IDs, \n",
"# not standard human gene symbols which are typically alphanumeric (e.g. BRCA1, TP53)\n",
"# These are likely probe IDs from a microarray platform that need to be mapped to gene symbols\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "9d136115",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "a9fab677",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:57:31.553730Z",
"iopub.status.busy": "2025-03-25T03:57:31.553629Z",
"iopub.status.idle": "2025-03-25T03:57:32.951176Z",
"shell.execute_reply": "2025-03-25T03:57:32.950644Z"
}
},
"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 = GSE84634\n",
"Line 6: !Series_title = Gene expression of peripheral blood mononuclear cells from adults with sickle cell disease (University of Chicago cohort)\n",
"Line 7: !Series_geo_accession = GSE84634\n",
"Line 8: !Series_status = Public on Sep 08 2017\n",
"Line 9: !Series_submission_date = Jul 20 2016\n",
"Line 10: !Series_last_update_date = Feb 18 2019\n",
"Line 11: !Series_pubmed_id = 28373264\n",
"Line 12: !Series_summary = Sickle cell disease is associated with systemic complications, many associated with either severity of disease or increased risk of mortality. We sought to identify a circulating gene expression profile whose predictive capacity spanned the spectrum of these poor outcomes in sickle cell disease.\n",
"Line 13: !Series_summary = The Training cohort consisted of patients with SCD who were prospectively recruited from the University of Illinois. The Testing cohort consisted of a combination of patients prospectively seen at two separate institutions including the University of Chicago and Howard University.\n",
"Line 14: !Series_overall_design = The gene expression of PBMC from 38 sickle cell disease patients from University of Chicago were analyzed.\n",
"Line 15: !Series_type = Expression profiling by array\n",
"Line 16: !Series_contributor = Zhengdeng,,Lei\n",
"Line 17: !Series_contributor = Ankit,,Desai\n",
"Line 18: !Series_contributor = Roberto,,Machado\n",
"Line 19: !Series_sample_id = GSM2243346\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Gene annotation preview:\n",
"{'ID': [2315100, 2315106, 2315109, 2315111, 2315113], 'GB_LIST': ['NR_024005,NR_034090,NR_024004,AK093685', 'DQ786314', nan, nan, 'DQ786265'], 'SPOT_ID': ['chr1:11884-14409', 'chr1:14760-15198', 'chr1:19408-19712', 'chr1:25142-25532', 'chr1:27563-27813'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['11884', '14760', '19408', '25142', '27563'], 'RANGE_STOP': ['14409', '15198', '19712', '25532', '27813'], 'total_probes': ['20', '8', '4', '4', '4'], 'gene_assignment': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---'], 'mrna_assignment': ['NR_024005 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 2, non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_034090 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 (DDX11L9), non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_024004 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 1, non-coding RNA. // chr1 // 100 // 75 // 15 // 15 // 0 /// AK093685 // GenBank // Homo sapiens cDNA FLJ36366 fis, clone THYMU2007824. // chr1 // 94 // 80 // 15 // 16 // 0 /// ENST00000513886 // ENSEMBL // cdna:known chromosome:GRCh37:16:61555:64090:1 gene:ENSG00000233614 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000518655 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000253101 // chr1 // 100 // 80 // 16 // 16 // 0', 'DQ786314 // GenBank // Homo sapiens clone HLS_IMAGE_811138 mRNA sequence. // chr1 // 100 // 38 // 3 // 3 // 0', '---', '---', 'DQ786265 // GenBank // Homo sapiens clone HLS_IMAGE_298685 mRNA sequence. // chr1 // 100 // 100 // 4 // 4 // 0'], 'category': ['main', 'main', '---', '---', 'main']}\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": "476eb3da",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "513f4641",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:57:32.952691Z",
"iopub.status.busy": "2025-03-25T03:57:32.952585Z",
"iopub.status.idle": "2025-03-25T03:57:36.495479Z",
"shell.execute_reply": "2025-03-25T03:57:36.494946Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene expression data shape: (22011, 38)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene annotation data shape: (1153375, 12)\n",
"Mapping dataframe shape: (316481, 2)\n",
"First few rows of mapping dataframe:\n",
" ID Gene\n",
"0 2315100 NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-As...\n",
"1 2315106 ---\n",
"2 2315109 ---\n",
"3 2315111 ---\n",
"4 2315113 ---\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Mapped gene expression data shape: (48895, 38)\n",
"First few rows of gene expression data:\n",
" GSM2243346 GSM2243347 GSM2243348 GSM2243349 GSM2243350 GSM2243351 \\\n",
"Gene \n",
"A- 15.509117 15.397530 15.808708 15.439154 15.664632 15.683596 \n",
"A-2 2.343726 2.239466 2.320720 2.421121 2.389999 2.265380 \n",
"A-52 4.393986 4.424308 4.358994 4.405801 4.404844 4.336857 \n",
"A-E 1.381988 1.407230 1.351711 1.373573 1.373060 1.288748 \n",
"A-I 4.520968 4.413596 4.748982 4.810093 4.669394 4.478377 \n",
"\n",
" GSM2243352 GSM2243353 GSM2243354 GSM2243355 ... GSM2243374 \\\n",
"Gene ... \n",
"A- 14.417419 15.318694 15.801011 15.815661 ... 15.801735 \n",
"A-2 2.383855 2.341696 2.324946 2.263749 ... 2.363010 \n",
"A-52 4.457693 4.427117 4.329272 4.250242 ... 4.407136 \n",
"A-E 1.413379 1.367112 1.313429 1.266908 ... 1.364211 \n",
"A-I 4.570401 4.527268 4.713956 4.606424 ... 4.691553 \n",
"\n",
" GSM2243375 GSM2243376 GSM2243377 GSM2243378 GSM2243379 GSM2243380 \\\n",
"Gene \n",
"A- 15.851646 15.128587 15.012407 15.457966 15.585657 15.258049 \n",
"A-2 2.355550 2.423941 2.246307 2.403882 2.144101 2.256434 \n",
"A-52 4.411432 4.457067 4.421105 4.426387 4.514809 4.412663 \n",
"A-E 1.363080 1.473665 1.406145 1.441528 1.273675 1.407616 \n",
"A-I 4.833840 4.519637 4.564514 4.714724 4.344824 4.619879 \n",
"\n",
" GSM2243381 GSM2243382 GSM2243383 \n",
"Gene \n",
"A- 15.716938 15.370655 15.709934 \n",
"A-2 2.337742 2.305593 2.359541 \n",
"A-52 4.469582 4.386699 4.432339 \n",
"A-E 1.399194 1.350216 1.309320 \n",
"A-I 4.725567 4.545077 4.431872 \n",
"\n",
"[5 rows x 38 columns]\n",
"After normalization, gene expression data shape: (18418, 38)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene expression data saved to ../../output/preprocess/Sickle_Cell_Anemia/gene_data/GSE84634.csv\n"
]
}
],
"source": [
"# 1. Identify the relevant columns for mapping\n",
"# From examining the gene annotation data, we can see:\n",
"# - 'ID' column contains numeric identifiers matching those in the gene expression data\n",
"# - 'gene_assignment' column contains gene symbol information\n",
"\n",
"# First, obtain the gene expression data if we haven't already\n",
"gene_data = get_genetic_data(matrix_file)\n",
"print(f\"Gene expression data shape: {gene_data.shape}\")\n",
"\n",
"# Get gene annotation data from SOFT file\n",
"gene_annotation = get_gene_annotation(soft_file)\n",
"print(f\"Gene annotation data shape: {gene_annotation.shape}\")\n",
"\n",
"# 2. Create mapping dataframe with ID and gene symbols\n",
"# Extract the 'ID' and 'gene_assignment' columns for mapping\n",
"mapping_df = get_gene_mapping(gene_annotation, 'ID', 'gene_assignment')\n",
"print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
"print(f\"First few rows of mapping dataframe:\")\n",
"print(mapping_df.head())\n",
"\n",
"# 3. Apply the mapping to convert probe-level measurements to gene expression data\n",
"gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
"print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n",
"print(f\"First few rows of gene expression data:\")\n",
"print(gene_data.head())\n",
"\n",
"# Apply gene symbol normalization to handle synonyms\n",
"gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"After normalization, gene expression data shape: {gene_data.shape}\")\n",
"\n",
"# Save gene expression data to output file\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"gene_data.to_csv(out_gene_data_file)\n",
"print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "185781a1",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "4c52d163",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:57:36.497130Z",
"iopub.status.busy": "2025-03-25T03:57:36.497007Z",
"iopub.status.idle": "2025-03-25T03:57:42.341987Z",
"shell.execute_reply": "2025-03-25T03:57:42.341361Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalized gene data shape: (18418, 38)\n",
"First few genes with their expression values after normalization:\n",
" GSM2243346 GSM2243347 GSM2243348 GSM2243349 GSM2243350 \\\n",
"Gene \n",
"A1BG 1.629561 1.650178 1.623354 1.674790 1.693946 \n",
"A1BG-AS1 1.629561 1.650178 1.623354 1.674790 1.693946 \n",
"A1CF 1.021493 1.015058 0.983417 1.029269 0.977699 \n",
"A2M 2.297381 2.518467 2.445836 2.369931 2.310326 \n",
"A2ML1 1.144764 1.230670 1.232296 1.259902 1.492003 \n",
"\n",
" GSM2243351 GSM2243352 GSM2243353 GSM2243354 GSM2243355 ... \\\n",
"Gene ... \n",
"A1BG 1.585265 1.601531 1.629005 1.595809 1.503266 ... \n",
"A1BG-AS1 1.585265 1.601531 1.629005 1.595809 1.503266 ... \n",
"A1CF 0.943049 1.038536 1.008471 0.984444 0.999792 ... \n",
"A2M 2.350215 2.275702 2.481097 2.344658 2.395414 ... \n",
"A2ML1 1.157765 1.343480 1.225757 1.160672 1.288853 ... \n",
"\n",
" GSM2243374 GSM2243375 GSM2243376 GSM2243377 GSM2243378 \\\n",
"Gene \n",
"A1BG 1.593967 1.657989 1.669062 1.657994 1.656727 \n",
"A1BG-AS1 1.593967 1.657989 1.669062 1.657994 1.656727 \n",
"A1CF 1.006683 1.044714 1.015970 1.084542 1.058144 \n",
"A2M 2.334292 2.218342 2.386534 2.445819 2.368546 \n",
"A2ML1 1.212673 1.336245 1.480550 1.279770 1.217620 \n",
"\n",
" GSM2243379 GSM2243380 GSM2243381 GSM2243382 GSM2243383 \n",
"Gene \n",
"A1BG 1.507334 1.628379 1.617256 1.673631 1.555988 \n",
"A1BG-AS1 1.507334 1.628379 1.617256 1.673631 1.555988 \n",
"A1CF 1.015978 0.996713 1.014247 0.910722 0.994150 \n",
"A2M 2.437949 2.281662 2.289033 2.366515 2.444647 \n",
"A2ML1 1.362562 1.315409 1.179588 1.379166 1.280339 \n",
"\n",
"[5 rows x 38 columns]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalized gene data saved to ../../output/preprocess/Sickle_Cell_Anemia/gene_data/GSE84634.csv\n",
"Raw clinical data shape: (3, 39)\n",
"Clinical features:\n",
" GSM2243346 GSM2243347 GSM2243348 GSM2243349 \\\n",
"Sickle_Cell_Anemia 1.0 1.0 1.0 1.0 \n",
"\n",
" GSM2243350 GSM2243351 GSM2243352 GSM2243353 \\\n",
"Sickle_Cell_Anemia 1.0 1.0 1.0 1.0 \n",
"\n",
" GSM2243354 GSM2243355 ... GSM2243374 GSM2243375 \\\n",
"Sickle_Cell_Anemia 1.0 1.0 ... 1.0 1.0 \n",
"\n",
" GSM2243376 GSM2243377 GSM2243378 GSM2243379 \\\n",
"Sickle_Cell_Anemia 1.0 1.0 1.0 1.0 \n",
"\n",
" GSM2243380 GSM2243381 GSM2243382 GSM2243383 \n",
"Sickle_Cell_Anemia 1.0 1.0 1.0 1.0 \n",
"\n",
"[1 rows x 38 columns]\n",
"Clinical features saved to ../../output/preprocess/Sickle_Cell_Anemia/clinical_data/GSE84634.csv\n",
"Linked data shape: (38, 18419)\n",
"Linked data preview (first 5 rows, first 5 columns):\n",
" Sickle_Cell_Anemia A1BG A1BG-AS1 A1CF A2M\n",
"GSM2243346 1.0 1.629561 1.629561 1.021493 2.297381\n",
"GSM2243347 1.0 1.650178 1.650178 1.015058 2.518467\n",
"GSM2243348 1.0 1.623354 1.623354 0.983417 2.445836\n",
"GSM2243349 1.0 1.674790 1.674790 1.029269 2.369931\n",
"GSM2243350 1.0 1.693946 1.693946 0.977699 2.310326\n",
"Missing values before handling:\n",
" Trait (Sickle_Cell_Anemia) missing: 0 out of 38\n",
" Genes with >20% missing: 0\n",
" Samples with >5% missing genes: 0\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Data shape after handling missing values: (38, 18419)\n",
"Quartiles for 'Sickle_Cell_Anemia':\n",
" 25%: 1.0\n",
" 50% (Median): 1.0\n",
" 75%: 1.0\n",
"Min: 1.0\n",
"Max: 1.0\n",
"The distribution of the feature 'Sickle_Cell_Anemia' in this dataset is severely biased.\n",
"\n",
"Data was determined to be unusable or empty and was not saved\n"
]
}
],
"source": [
"# 1. Normalize gene symbols in the gene expression data\n",
"normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
"print(\"First few genes with their expression values after normalization:\")\n",
"print(normalized_gene_data.head())\n",
"\n",
"# Save the normalized 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",
"# 2. Check if trait data is available before proceeding with clinical data extraction\n",
"if trait_row is None:\n",
" print(\"Trait row is None. Cannot extract trait information from clinical data.\")\n",
" # Create an empty dataframe for clinical features\n",
" clinical_features = pd.DataFrame()\n",
" \n",
" # Create an empty dataframe for linked data\n",
" linked_data = pd.DataFrame()\n",
" \n",
" # Validate and save cohort info\n",
" validate_and_save_cohort_info(\n",
" is_final=True, \n",
" cohort=cohort, \n",
" info_path=json_path, \n",
" is_gene_available=True, \n",
" is_trait_available=False, # Trait data is not available\n",
" is_biased=True, # Not applicable but required\n",
" df=pd.DataFrame(), # Empty dataframe\n",
" note=f\"Dataset contains gene expression data but lacks clear trait indicators for {trait} status.\"\n",
" )\n",
" print(\"Data was determined to be unusable due to missing trait indicators and was not saved\")\n",
"else:\n",
" try:\n",
" # Get the file paths for the matrix file to extract clinical data\n",
" _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
" \n",
" # Get raw clinical data from the matrix file\n",
" _, clinical_raw = get_background_and_clinical_data(matrix_file)\n",
" \n",
" # Verify clinical data structure\n",
" print(\"Raw clinical data shape:\", clinical_raw.shape)\n",
" \n",
" # Extract clinical features using the defined conversion functions\n",
" clinical_features = geo_select_clinical_features(\n",
" clinical_df=clinical_raw,\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",
" print(\"Clinical features:\")\n",
" print(clinical_features)\n",
" \n",
" # Save clinical features to file\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" clinical_features.to_csv(out_clinical_data_file)\n",
" print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
" \n",
" # 3. Link clinical and genetic data\n",
" linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
" print(f\"Linked data shape: {linked_data.shape}\")\n",
" print(\"Linked data preview (first 5 rows, first 5 columns):\")\n",
" print(linked_data.iloc[:5, :5])\n",
" \n",
" # 4. Handle missing values\n",
" print(\"Missing values before handling:\")\n",
" print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n",
" if 'Age' in linked_data.columns:\n",
" print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n",
" if 'Gender' in linked_data.columns:\n",
" print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n",
" \n",
" gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n",
" print(f\" Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n",
" print(f\" Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n",
" \n",
" cleaned_data = handle_missing_values(linked_data, trait)\n",
" print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n",
" \n",
" # 5. Evaluate bias in trait and demographic features\n",
" is_trait_biased = False\n",
" if len(cleaned_data) > 0:\n",
" trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n",
" is_trait_biased = trait_biased\n",
" else:\n",
" print(\"No data remains after handling missing values.\")\n",
" is_trait_biased = True\n",
" \n",
" # 6. Final validation and save\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_trait_biased, \n",
" df=cleaned_data,\n",
" note=f\"Dataset contains only {trait} patients with no healthy controls, making it unsuitable for case-control analysis.\"\n",
" )\n",
" \n",
" # 7. Save if usable\n",
" if is_usable and len(cleaned_data) > 0:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" cleaned_data.to_csv(out_data_file)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
" else:\n",
" print(\"Data was determined to be unusable or empty and was not saved\")\n",
" \n",
" except Exception as e:\n",
" print(f\"Error processing data: {e}\")\n",
" # Handle the error case by still recording cohort info\n",
" validate_and_save_cohort_info(\n",
" is_final=True, \n",
" cohort=cohort, \n",
" info_path=json_path, \n",
" is_gene_available=True, \n",
" is_trait_available=False, # Mark as not available due to processing issues\n",
" is_biased=True, \n",
" df=pd.DataFrame(), # Empty dataframe\n",
" note=f\"Error processing data for {trait}: {str(e)}\"\n",
" )\n",
" print(\"Data was determined to be unusable and was not saved\")"
]
}
],
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.16"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|