File size: 49,377 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 776 777 778 779 780 781 782 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "366c5f56",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:06:21.298677Z",
"iopub.status.busy": "2025-03-25T07:06:21.298338Z",
"iopub.status.idle": "2025-03-25T07:06:21.462558Z",
"shell.execute_reply": "2025-03-25T07:06:21.462228Z"
}
},
"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 = \"Cardiovascular_Disease\"\n",
"cohort = \"GSE228783\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Cardiovascular_Disease\"\n",
"in_cohort_dir = \"../../input/GEO/Cardiovascular_Disease/GSE228783\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Cardiovascular_Disease/GSE228783.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Cardiovascular_Disease/gene_data/GSE228783.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE228783.csv\"\n",
"json_path = \"../../output/preprocess/Cardiovascular_Disease/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "414b843a",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "12d50859",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:06:21.463945Z",
"iopub.status.busy": "2025-03-25T07:06:21.463813Z",
"iopub.status.idle": "2025-03-25T07:06:21.788436Z",
"shell.execute_reply": "2025-03-25T07:06:21.788080Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"Inter-patient heterogeneity in the hepatic ischemia-reperfusion injury transcriptome: implications for research and diagnostics\"\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: ['tissue: liver'], 1: ['patient: 1', 'patient: 2', 'patient: 3', 'patient: 4', 'patient: 5', 'patient: 6', 'patient: 7', 'patient: 8', 'patient: 9', 'patient: 10', 'patient: 11', 'patient: pat 1', 'patient: pat 2', 'patient: pat 3', 'patient: pat 4', 'patient: pat 5', 'patient: pat 6', 'patient: pat 7', 'patient: pat 8', 'patient: pat 9', 'patient: pat 10', 'patient: pat 11', 'patient: pat 12', 'patient: pat 13', 'patient: pat 14', 'patient: pat 15', 'patient: pat 16', 'patient: pat 17', 'patient: pat 18', 'patient: pat 19'], 2: ['disease: CRC Met', 'disease: CCC', 'disease: HCC', 'disease: other'], 3: ['steatosis: NA', 'steatosis: <5%', 'steatosis: >20%'], 4: ['time point: 0', 'time point: 30', 'time point: 60', 'time point: 120', 'time point: 180', 'time point: 360', 'time point: 20', 'time point: 12', 'time point: 190w', 'time point: 230w', 'time point: 128', 'time point: 50w', 'time point: 125', 'time point: 93w', 'time point: 123w', 'time point: 150', 'time point: 195w', 'time point: 224w', 'time point: 1', 'time point: 3', 'time point: 2']}\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": "7b132fe9",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "1bc1de2a",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:06:21.789833Z",
"iopub.status.busy": "2025-03-25T07:06:21.789727Z",
"iopub.status.idle": "2025-03-25T07:06:21.801410Z",
"shell.execute_reply": "2025-03-25T07:06:21.801128Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Preview of selected clinical features:\n",
"{'tissue': [nan], 'patient': [nan], 'disease': [1.0], 'steatosis': [nan], 'time point': [nan]}\n",
"Clinical data saved to ../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE228783.csv\n"
]
}
],
"source": [
"import os\n",
"import pandas as pd\n",
"import json\n",
"from typing import Optional, Callable, Dict, Any\n",
"\n",
"# 1. Review the data to determine if gene expression data is likely available\n",
"# Based on the series title and overall design, this appears to be a gene expression study \n",
"# of liver samples during ischemia-reperfusion injury\n",
"is_gene_available = True\n",
"\n",
"# 2. Determine availability of trait, age, and gender data\n",
"\n",
"# 2.1 Identify rows where trait, age, and gender data might be found\n",
"# Looking at sample characteristics, we can see:\n",
"# Row 2 contains 'disease' information which could be related to cardiovascular complications\n",
"# Row 4 contains 'time point' information which could indicate ischemia-reperfusion timing\n",
"trait_row = 2 # Disease information row\n",
"age_row = None # No age data available\n",
"gender_row = None # No gender data available\n",
"\n",
"# 2.2 Define conversion functions\n",
"def convert_trait(value: str) -> int:\n",
" \"\"\"Convert disease information to binary trait values for Cardiovascular Disease.\"\"\"\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract the value after the colon\n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" # The study focuses on liver ischemia-reperfusion injury\n",
" # While the primary focus is on liver diseases, ischemia-reperfusion injury\n",
" # has cardiovascular implications due to blood flow disruption\n",
" # For this analysis, we'll consider HCC and CCC as having higher cardiovascular risk\n",
" # due to their vascular involvement\n",
" if value.upper() in [\"HCC\", \"CCC\"]:\n",
" return 1 # These liver diseases often have vascular involvement\n",
" elif value.upper() in [\"CRC MET\", \"OTHER\"]:\n",
" return 0 # Less clear cardiovascular involvement\n",
" else:\n",
" return None\n",
"\n",
"# Age and gender conversion functions are defined but won't be used\n",
"def convert_age(value: str) -> Optional[float]:\n",
" return None # Not available in this dataset\n",
"\n",
"def convert_gender(value: str) -> Optional[int]:\n",
" return None # Not available in this dataset\n",
"\n",
"# 3. Save metadata about the cohort\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. If trait data is available, extract clinical features\n",
"if trait_row is not None:\n",
" try:\n",
" # In previous steps, clinical_data was obtained directly from sample_characteristics\n",
" # We need to reconstruct it from the sample characteristics dictionary\n",
" \n",
" # Recreate clinical_data from the sample characteristics dictionary\n",
" clinical_data = pd.DataFrame()\n",
" # Reconstruct clinical data from sample characteristics dictionary\n",
" sample_characteristics = {0: ['tissue: liver'], \n",
" 1: ['patient: 1', 'patient: 2', 'patient: 3', 'patient: 4', \n",
" 'patient: 5', 'patient: 6', 'patient: 7', 'patient: 8', \n",
" 'patient: 9', 'patient: 10', 'patient: 11', 'patient: pat 1', \n",
" 'patient: pat 2', 'patient: pat 3', 'patient: pat 4', \n",
" 'patient: pat 5', 'patient: pat 6', 'patient: pat 7', \n",
" 'patient: pat 8', 'patient: pat 9', 'patient: pat 10', \n",
" 'patient: pat 11', 'patient: pat 12', 'patient: pat 13', \n",
" 'patient: pat 14', 'patient: pat 15', 'patient: pat 16', \n",
" 'patient: pat 17', 'patient: pat 18', 'patient: pat 19'], \n",
" 2: ['disease: CRC Met', 'disease: CCC', 'disease: HCC', 'disease: other'], \n",
" 3: ['steatosis: NA', 'steatosis: <5%', 'steatosis: >20%'], \n",
" 4: ['time point: 0', 'time point: 30', 'time point: 60', \n",
" 'time point: 120', 'time point: 180', 'time point: 360', \n",
" 'time point: 20', 'time point: 12', 'time point: 190w', \n",
" 'time point: 230w', 'time point: 128', 'time point: 50w', \n",
" 'time point: 125', 'time point: 93w', 'time point: 123w', \n",
" 'time point: 150', 'time point: 195w', 'time point: 224w', \n",
" 'time point: 1', 'time point: 3', 'time point: 2']}\n",
" \n",
" for row_idx, values in sample_characteristics.items():\n",
" # Create a row for each characteristic with sample IDs as columns\n",
" feature_name = values[0].split(\":\")[0].strip()\n",
" row_data = {f\"Sample_{i}\": value for i, value in enumerate(values)}\n",
" feature_row = pd.DataFrame([row_data], index=[feature_name])\n",
" clinical_data = pd.concat([clinical_data, feature_row])\n",
" \n",
" clinical_data = clinical_data.transpose() # Transpose so samples are rows\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 selected clinical features:\")\n",
" print(preview)\n",
" \n",
" # Save the clinical data\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
" print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
" except Exception as e:\n",
" print(f\"Error processing clinical data: {e}\")\n",
" # If there was an error, we'll still note that trait data is available\n",
" # but we couldn't process it correctly\n",
" print(\"Failed to process the clinical data. The dataset may still be usable once the processing issue is fixed.\")\n"
]
},
{
"cell_type": "markdown",
"id": "e253ea56",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "a377b4ef",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:06:21.802634Z",
"iopub.status.busy": "2025-03-25T07:06:21.802535Z",
"iopub.status.idle": "2025-03-25T07:06:22.394552Z",
"shell.execute_reply": "2025-03-25T07:06:22.394229Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Matrix file found: ../../input/GEO/Cardiovascular_Disease/GSE228783/GSE228783_series_matrix.txt.gz\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene data shape: (49386, 152)\n",
"First 20 gene/probe identifiers:\n",
"Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n",
" '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n",
" '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n",
" '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n",
" '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\n",
" dtype='object', name='ID')\n"
]
}
],
"source": [
"# 1. Get the SOFT and matrix file paths again \n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"print(f\"Matrix file found: {matrix_file}\")\n",
"\n",
"# 2. Use the get_genetic_data function from the library to get the gene_data\n",
"try:\n",
" gene_data = get_genetic_data(matrix_file)\n",
" print(f\"Gene data shape: {gene_data.shape}\")\n",
" \n",
" # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
" print(\"First 20 gene/probe identifiers:\")\n",
" print(gene_data.index[:20])\n",
"except Exception as e:\n",
" print(f\"Error extracting gene data: {e}\")\n"
]
},
{
"cell_type": "markdown",
"id": "0c2fe05d",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "9e12aa3e",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:06:22.396069Z",
"iopub.status.busy": "2025-03-25T07:06:22.395849Z",
"iopub.status.idle": "2025-03-25T07:06:22.397805Z",
"shell.execute_reply": "2025-03-25T07:06:22.397515Z"
}
},
"outputs": [],
"source": [
"# Looking at the gene identifiers in the gene expression data\n",
"# These identifiers appear to be in the format of probe IDs (e.g., 11715100_at) and not standard gene symbols\n",
"# Standard human gene symbols would be like BRCA1, TP53, etc.\n",
"# These probe IDs need to be mapped to actual gene symbols for meaningful analysis\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "23ed2687",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "60d2df22",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:06:22.399161Z",
"iopub.status.busy": "2025-03-25T07:06:22.399056Z",
"iopub.status.idle": "2025-03-25T07:06:38.340799Z",
"shell.execute_reply": "2025-03-25T07:06:38.340168Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Gene annotation preview:\n",
"Columns in gene annotation: ['ID', 'GeneChip Array', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Transcript ID(Array Design)', 'Target Description', 'Representative Public ID', 'Archival UniGene Cluster', 'UniGene ID', 'Genome Version', 'Alignments', 'Gene Title', 'Gene Symbol', 'Chromosomal Location', 'GB_LIST', 'SPOT_ID', 'Unigene Cluster Type', 'Ensembl', 'Entrez Gene', 'SwissProt', 'EC', 'OMIM', 'RefSeq Protein ID', 'RefSeq Transcript ID', 'FlyBase', 'AGI', 'WormBase', 'MGI Name', 'RGD Name', 'SGD accession number', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function', 'Pathway', 'InterPro', 'Trans Membrane', 'QTL', 'Annotation Description', 'Annotation Transcript Cluster', 'Transcript Assignments', 'Annotation Notes']\n",
"{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p21.3', 'chr6p21.3', 'chr6p21.3', 'chr19p13.3', 'chr17q25.1'], 'GB_LIST': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942,NM_152362', 'NM_178160'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['---', 'ENSG00000178458', '---', 'ENSG00000185361', 'ENSG00000183034'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '---', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575', 'NP_835454'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362', 'NM_178160'], 'FlyBase': ['---', '---', '---', '---', '---'], 'AGI': ['---', '---', '---', '---', '---'], 'WormBase': ['---', '---', '---', '---', '---'], 'MGI Name': ['---', '---', '---', '---', '---'], 'RGD Name': ['---', '---', '---', '---', '---'], 'SGD accession number': ['---', '---', '---', '---', '---'], 'Gene Ontology Biological Process': ['0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '---', '---'], 'Gene Ontology Cellular Component': ['0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '---', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '---', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['---', '---', '---', '---', 'IPR004878 // Protein of unknown function DUF270 // 1.0E-6 /// IPR004878 // Protein of unknown function DUF270 // 1.0E-13'], 'Trans Membrane': ['---', '---', '---', '---', 'NP_835454.1 // span:30-52,62-81,101-120,135-157,240-262,288-310,327-349,369-391,496-515,525-547 // numtm:10'], 'QTL': ['---', '---', '---', '---', '---'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 2 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 5 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 3 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['NM_003534(11)', 'BC079835(11),NM_003534(11)', 'NM_003534(11)', 'BC017672(11),BC044250(9),ENST00000327473(11),NM_001167942(11),NM_152362(11)', 'ENST00000331427(11),ENST00000426069(11),NM_178160(11)'], 'Transcript Assignments': ['NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'BC079835 // Homo sapiens histone cluster 1, H3g, mRNA (cDNA clone IMAGE:5935692). // gb_htc // 11 // --- /// ENST00000321285 // cdna:known chromosome:GRCh37:6:26271202:26271612:-1 gene:ENSG00000178458 // ensembl // 11 // --- /// GENSCAN00000044911 // cdna:Genscan chromosome:GRCh37:6:26271202:26271612:-1 // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // cdna:known chromosome:GRCh37:19:4639530:4653952:1 gene:ENSG00000185361 // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // ---', 'ENST00000331427 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// ENST00000426069 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['BC079835 // gb_htc // 6 // Cross Hyb Matching Probes', '---', 'GENSCAN00000044911 // ensembl // 4 // Cross Hyb Matching Probes /// ENST00000321285 // ensembl // 4 // Cross Hyb Matching Probes /// BC079835 // gb_htc // 7 // Cross Hyb Matching Probes', '---', 'GENSCAN00000031612 // ensembl // 8 // Cross Hyb Matching Probes']}\n",
"\n",
"Searching for platform information in SOFT file:\n",
"Platform ID not found in first 100 lines\n",
"\n",
"Searching for gene symbol information in SOFT file:\n",
"Found references to gene symbols:\n",
"#Gene Symbol =\n",
"ID\tGeneChip Array\tSpecies Scientific Name\tAnnotation Date\tSequence Type\tSequence Source\tTranscript ID(Array Design)\tTarget Description\tRepresentative Public ID\tArchival UniGene Cluster\tUniGene ID\tGenome Version\tAlignments\tGene Title\tGene Symbol\tChromosomal Location\tGB_LIST\tSPOT_ID\tUnigene Cluster Type\tEnsembl\tEntrez Gene\tSwissProt\tEC\tOMIM\tRefSeq Protein ID\tRefSeq Transcript ID\tFlyBase\tAGI\tWormBase\tMGI Name\tRGD Name\tSGD accession number\tGene Ontology Biological Process\tGene Ontology Cellular Component\tGene Ontology Molecular Function\tPathway\tInterPro\tTrans Membrane\tQTL\tAnnotation Description\tAnnotation Transcript Cluster\tTranscript Assignments\tAnnotation Notes\n",
"\n",
"Checking for additional annotation files in the directory:\n",
"[]\n"
]
}
],
"source": [
"# 1. 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",
"# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
"print(\"\\nGene annotation preview:\")\n",
"print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
"print(preview_df(gene_annotation, n=5))\n",
"\n",
"# Let's look for platform information in the SOFT file to understand the annotation better\n",
"print(\"\\nSearching for platform information in SOFT file:\")\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" for i, line in enumerate(f):\n",
" if '!Series_platform_id' in line:\n",
" print(line.strip())\n",
" break\n",
" if i > 100: # Limit search to first 100 lines\n",
" print(\"Platform ID not found in first 100 lines\")\n",
" break\n",
"\n",
"# Check if the SOFT file includes any reference to gene symbols\n",
"print(\"\\nSearching for gene symbol information in SOFT file:\")\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" gene_symbol_lines = []\n",
" for i, line in enumerate(f):\n",
" if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n",
" gene_symbol_lines.append(line.strip())\n",
" if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n",
" break\n",
" \n",
" if gene_symbol_lines:\n",
" print(\"Found references to gene symbols:\")\n",
" for line in gene_symbol_lines[:5]: # Show just first 5 matches\n",
" print(line)\n",
" else:\n",
" print(\"No explicit gene symbol references found in first 1000 lines\")\n",
"\n",
"# Look for alternative annotation files or references in the directory\n",
"print(\"\\nChecking for additional annotation files in the directory:\")\n",
"all_files = os.listdir(in_cohort_dir)\n",
"print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n"
]
},
{
"cell_type": "markdown",
"id": "551cfee8",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "461b9414",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:06:38.342468Z",
"iopub.status.busy": "2025-03-25T07:06:38.342339Z",
"iopub.status.idle": "2025-03-25T07:06:40.808791Z",
"shell.execute_reply": "2025-03-25T07:06:40.808147Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene mapping shape: (49384, 2)\n",
"Sample of gene mapping:\n",
" ID Gene\n",
"0 11715100_at HIST1H3G\n",
"1 11715101_s_at HIST1H3G\n",
"2 11715102_x_at HIST1H3G\n",
"3 11715103_x_at TNFAIP8L1\n",
"4 11715104_s_at OTOP2\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene expression data shape after mapping: (19521, 152)\n",
"Sample of gene expression data:\n",
" GSM7136321 GSM7136322 GSM7136323 GSM7136324 GSM7136325 GSM7136326 \\\n",
"Gene \n",
"A1BG 12.331240 12.400180 12.220780 12.314790 12.320090 12.188350 \n",
"A1CF 20.535768 19.749593 19.805032 19.829038 19.083230 18.914003 \n",
"A2BP1 24.275731 24.581101 23.720731 24.487690 25.114570 24.354993 \n",
"A2LD1 5.436063 5.250350 4.854429 4.837758 4.288509 4.596958 \n",
"A2M 12.322190 12.347180 12.328560 12.215300 12.430240 12.470340 \n",
"\n",
" GSM7136327 GSM7136328 GSM7136329 GSM7136330 ... GSM7136471 \\\n",
"Gene ... \n",
"A1BG 12.277750 12.681400 12.301720 12.680710 ... 12.658040 \n",
"A1CF 19.153251 18.875642 19.114262 19.459663 ... 20.654768 \n",
"A2BP1 24.718140 24.367485 24.515163 24.708162 ... 32.943854 \n",
"A2LD1 4.538619 4.274169 3.893469 3.767836 ... 5.941902 \n",
"A2M 12.358510 12.938990 12.798970 12.952340 ... 12.793390 \n",
"\n",
" GSM7136472 GSM7136473 GSM7136474 GSM7136475 GSM7136476 GSM7136477 \\\n",
"Gene \n",
"A1BG 12.266250 12.269730 12.404070 11.951360 12.193960 12.576380 \n",
"A1CF 20.090938 19.097046 18.963448 19.085113 20.753651 19.250723 \n",
"A2BP1 34.630446 30.697407 33.603114 32.538086 31.576277 29.814539 \n",
"A2LD1 4.790622 4.691540 4.758732 4.552613 4.042120 4.477151 \n",
"A2M 12.966040 12.486020 12.380550 12.211510 12.341370 13.119520 \n",
"\n",
" GSM7136478 GSM7136479 GSM7136480 \n",
"Gene \n",
"A1BG 12.634860 12.619390 12.760620 \n",
"A1CF 19.160037 19.050744 18.946244 \n",
"A2BP1 31.229101 30.087615 31.119074 \n",
"A2LD1 4.727412 4.686971 4.347549 \n",
"A2M 13.283110 13.122690 13.170930 \n",
"\n",
"[5 rows x 152 columns]\n",
"Gene expression data shape after normalization: (19298, 152)\n",
"Sample of normalized gene expression data:\n",
" GSM7136321 GSM7136322 GSM7136323 GSM7136324 GSM7136325 \\\n",
"Gene \n",
"A1BG 12.331240 12.400180 12.220780 12.314790 12.320090 \n",
"A1CF 20.535768 19.749593 19.805032 19.829038 19.083230 \n",
"A2M 12.322190 12.347180 12.328560 12.215300 12.430240 \n",
"A2ML1 4.097415 4.237847 4.280063 4.366853 4.634051 \n",
"A3GALT2 2.377258 2.470339 2.414795 2.482163 2.221069 \n",
"\n",
" GSM7136326 GSM7136327 GSM7136328 GSM7136329 GSM7136330 ... \\\n",
"Gene ... \n",
"A1BG 12.188350 12.277750 12.681400 12.301720 12.680710 ... \n",
"A1CF 18.914003 19.153251 18.875642 19.114262 19.459663 ... \n",
"A2M 12.470340 12.358510 12.938990 12.798970 12.952340 ... \n",
"A2ML1 4.636522 4.521736 4.458021 4.624085 4.671153 ... \n",
"A3GALT2 2.369390 2.369119 2.470181 2.336254 2.589919 ... \n",
"\n",
" GSM7136471 GSM7136472 GSM7136473 GSM7136474 GSM7136475 \\\n",
"Gene \n",
"A1BG 12.658040 12.266250 12.269730 12.404070 11.951360 \n",
"A1CF 20.654768 20.090938 19.097046 18.963448 19.085113 \n",
"A2M 12.793390 12.966040 12.486020 12.380550 12.211510 \n",
"A2ML1 6.878600 8.322906 5.879477 6.647265 6.830568 \n",
"A3GALT2 3.219765 3.285542 3.007490 3.324501 3.401053 \n",
"\n",
" GSM7136476 GSM7136477 GSM7136478 GSM7136479 GSM7136480 \n",
"Gene \n",
"A1BG 12.193960 12.576380 12.634860 12.619390 12.760620 \n",
"A1CF 20.753651 19.250723 19.160037 19.050744 18.946244 \n",
"A2M 12.341370 13.119520 13.283110 13.122690 13.170930 \n",
"A2ML1 6.200560 5.733786 6.200009 5.843473 5.833000 \n",
"A3GALT2 3.420812 3.140324 3.312281 3.273997 3.178747 \n",
"\n",
"[5 rows x 152 columns]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene expression data saved to ../../output/preprocess/Cardiovascular_Disease/gene_data/GSE228783.csv\n"
]
}
],
"source": [
"# 1. Based on the gene annotation data, determine which columns to use for mapping\n",
"probe_id_column = 'ID' # The probe identifiers column in the annotation data\n",
"gene_symbol_column = 'Gene Symbol' # The gene symbols column in the annotation data\n",
"\n",
"# 2. Get a gene mapping dataframe by extracting the two columns from the gene annotation dataframe\n",
"gene_mapping = get_gene_mapping(gene_annotation, probe_id_column, gene_symbol_column)\n",
"print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
"print(\"Sample of gene mapping:\")\n",
"print(gene_mapping.head())\n",
"\n",
"# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n",
"gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
"print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
"print(\"Sample of gene expression data:\")\n",
"print(gene_data.head())\n",
"\n",
"# Normalize gene symbols to handle synonyms\n",
"gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n",
"print(\"Sample of normalized gene expression data:\")\n",
"print(gene_data.head())\n",
"\n",
"# Save the gene expression data\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": "7e27ea48",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "559596d8",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T07:06:40.810264Z",
"iopub.status.busy": "2025-03-25T07:06:40.810148Z",
"iopub.status.idle": "2025-03-25T07:06:58.278705Z",
"shell.execute_reply": "2025-03-25T07:06:58.278029Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Clinical data shape: (5, 153)\n",
"Clinical data columns: Index(['!Sample_geo_accession', 'GSM7136321', 'GSM7136322', 'GSM7136323',\n",
" 'GSM7136324'],\n",
" dtype='object')\n",
"Clinical data index: RangeIndex(start=0, stop=5, step=1)\n",
"Sample characteristics dictionary:\n",
"Row 0: ['tissue: liver']\n",
"Row 1: ['patient: 1', 'patient: 2', 'patient: 3', 'patient: 4', 'patient: 5']\n",
"Row 2: ['disease: CRC Met', 'disease: CCC', 'disease: HCC', 'disease: other']\n",
"Row 3: ['steatosis: NA', 'steatosis: <5%', 'steatosis: >20%']\n",
"Row 4: ['time point: 0', 'time point: 30', 'time point: 60', 'time point: 120', 'time point: 180']\n",
"Clinical features shape: (1, 152)\n",
"Clinical features preview:\n",
"{'GSM7136321': [0.0], 'GSM7136322': [0.0], 'GSM7136323': [0.0], 'GSM7136324': [0.0], 'GSM7136325': [0.0], 'GSM7136326': [0.0], 'GSM7136327': [0.0], 'GSM7136328': [0.0], 'GSM7136329': [0.0], 'GSM7136330': [0.0], 'GSM7136331': [0.0], 'GSM7136332': [0.0], 'GSM7136333': [0.0], 'GSM7136334': [0.0], 'GSM7136335': [0.0], 'GSM7136336': [0.0], 'GSM7136337': [0.0], 'GSM7136338': [0.0], 'GSM7136339': [0.0], 'GSM7136340': [0.0], 'GSM7136341': [0.0], 'GSM7136342': [0.0], 'GSM7136343': [0.0], 'GSM7136344': [0.0], 'GSM7136345': [0.0], 'GSM7136346': [0.0], 'GSM7136347': [0.0], 'GSM7136348': [0.0], 'GSM7136349': [0.0], 'GSM7136350': [0.0], 'GSM7136351': [0.0], 'GSM7136352': [0.0], 'GSM7136353': [0.0], 'GSM7136354': [0.0], 'GSM7136355': [0.0], 'GSM7136356': [0.0], 'GSM7136357': [0.0], 'GSM7136358': [0.0], 'GSM7136359': [0.0], 'GSM7136360': [0.0], 'GSM7136361': [0.0], 'GSM7136362': [0.0], 'GSM7136363': [0.0], 'GSM7136364': [0.0], 'GSM7136365': [0.0], 'GSM7136366': [0.0], 'GSM7136367': [0.0], 'GSM7136368': [0.0], 'GSM7136369': [0.0], 'GSM7136370': [0.0], 'GSM7136371': [0.0], 'GSM7136372': [0.0], 'GSM7136373': [0.0], 'GSM7136374': [0.0], 'GSM7136375': [0.0], 'GSM7136376': [0.0], 'GSM7136377': [0.0], 'GSM7136378': [0.0], 'GSM7136379': [0.0], 'GSM7136380': [0.0], 'GSM7136381': [0.0], 'GSM7136382': [0.0], 'GSM7136383': [0.0], 'GSM7136384': [0.0], 'GSM7136385': [0.0], 'GSM7136386': [0.0], 'GSM7136387': [0.0], 'GSM7136388': [0.0], 'GSM7136389': [0.0], 'GSM7136390': [1.0], 'GSM7136391': [1.0], 'GSM7136392': [1.0], 'GSM7136393': [1.0], 'GSM7136394': [1.0], 'GSM7136395': [1.0], 'GSM7136396': [1.0], 'GSM7136397': [1.0], 'GSM7136398': [0.0], 'GSM7136399': [0.0], 'GSM7136400': [0.0], 'GSM7136401': [1.0], 'GSM7136402': [1.0], 'GSM7136403': [1.0], 'GSM7136404': [1.0], 'GSM7136405': [0.0], 'GSM7136406': [0.0], 'GSM7136407': [0.0], 'GSM7136408': [0.0], 'GSM7136409': [0.0], 'GSM7136410': [0.0], 'GSM7136411': [0.0], 'GSM7136412': [0.0], 'GSM7136413': [0.0], 'GSM7136414': [0.0], 'GSM7136415': [0.0], 'GSM7136416': [0.0], 'GSM7136417': [0.0], 'GSM7136418': [0.0], 'GSM7136419': [0.0], 'GSM7136420': [0.0], 'GSM7136421': [0.0], 'GSM7136422': [0.0], 'GSM7136423': [0.0], 'GSM7136424': [0.0], 'GSM7136425': [0.0], 'GSM7136426': [0.0], 'GSM7136427': [0.0], 'GSM7136428': [0.0], 'GSM7136429': [0.0], 'GSM7136430': [0.0], 'GSM7136431': [0.0], 'GSM7136432': [0.0], 'GSM7136433': [0.0], 'GSM7136434': [0.0], 'GSM7136435': [0.0], 'GSM7136436': [0.0], 'GSM7136437': [0.0], 'GSM7136438': [0.0], 'GSM7136439': [0.0], 'GSM7136440': [0.0], 'GSM7136441': [0.0], 'GSM7136442': [0.0], 'GSM7136443': [0.0], 'GSM7136444': [0.0], 'GSM7136445': [0.0], 'GSM7136446': [0.0], 'GSM7136447': [0.0], 'GSM7136448': [0.0], 'GSM7136449': [0.0], 'GSM7136450': [0.0], 'GSM7136451': [0.0], 'GSM7136452': [0.0], 'GSM7136453': [0.0], 'GSM7136454': [0.0], 'GSM7136455': [0.0], 'GSM7136456': [0.0], 'GSM7136457': [1.0], 'GSM7136458': [1.0], 'GSM7136460': [1.0], 'GSM7136462': [1.0], 'GSM7136465': [0.0], 'GSM7136468': [0.0], 'GSM7136471': [0.0], 'GSM7136472': [0.0], 'GSM7136473': [0.0], 'GSM7136474': [0.0], 'GSM7136475': [0.0], 'GSM7136476': [0.0], 'GSM7136477': [1.0], 'GSM7136478': [1.0], 'GSM7136479': [1.0], 'GSM7136480': [1.0]}\n",
"Clinical data saved to ../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE228783.csv\n",
"Linked data shape: (152, 19299)\n",
"Linked data preview (first 5 rows, 5 columns):\n",
" Cardiovascular_Disease A1BG A1CF A2M A2ML1\n",
"GSM7136321 0.0 12.33124 20.535768 12.32219 4.097415\n",
"GSM7136322 0.0 12.40018 19.749593 12.34718 4.237847\n",
"GSM7136323 0.0 12.22078 19.805032 12.32856 4.280063\n",
"GSM7136324 0.0 12.31479 19.829038 12.21530 4.366853\n",
"GSM7136325 0.0 12.32009 19.083230 12.43024 4.634051\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Linked data shape after handling missing values: (152, 19299)\n",
"For the feature 'Cardiovascular_Disease', the least common label is '1.0' with 20 occurrences. This represents 13.16% of the dataset.\n",
"The distribution of the feature 'Cardiovascular_Disease' in this dataset is fine.\n",
"\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Linked data saved to ../../output/preprocess/Cardiovascular_Disease/GSE228783.csv\n"
]
}
],
"source": [
"# 1. Gene symbols were already normalized in step 6\n",
"\n",
"# 2. Load the clinical data (from scratch to ensure we have the correct structure)\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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",
"# Print clinical data structure to better understand it\n",
"print(\"Clinical data shape:\", clinical_data.shape)\n",
"print(\"Clinical data columns:\", clinical_data.columns[:5]) \n",
"print(\"Clinical data index:\", clinical_data.index[:5])\n",
"\n",
"# Get sample characteristics dictionary to confirm the structure\n",
"sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
"print(\"Sample characteristics dictionary:\")\n",
"for key, values in sample_characteristics_dict.items():\n",
" print(f\"Row {key}: {values[:5]}\")\n",
"\n",
"# Define conversion functions that match the actual data in step 2\n",
"def convert_trait(value: str) -> int:\n",
" \"\"\"Convert disease information to binary trait values for Cardiovascular Disease.\"\"\"\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" \n",
" # Extract the value after the colon\n",
" if isinstance(value, str) and \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" # From step 2 analysis: HCC and CCC considered higher cardiovascular risk\n",
" if isinstance(value, str) and value.upper() in [\"HCC\", \"CCC\"]:\n",
" return 1 # These liver diseases often have vascular involvement\n",
" elif isinstance(value, str) and value.upper() in [\"CRC MET\", \"OTHER\"]:\n",
" return 0 # Less clear cardiovascular involvement\n",
" else:\n",
" return None\n",
"\n",
"# Create empty placeholder functions since age and gender aren't available\n",
"def convert_age(value: str) -> None:\n",
" return None\n",
"\n",
"def convert_gender(value: str) -> None:\n",
" return None\n",
"\n",
"# Define the correct row for trait based on step 2 (disease information is in row 2)\n",
"trait_row = 2\n",
"age_row = None # No age data available\n",
"gender_row = None # No gender data available\n",
"\n",
"# Try to extract clinical features with safe error handling\n",
"try:\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",
" print(f\"Clinical features shape: {clinical_features.shape}\")\n",
" print(\"Clinical features preview:\")\n",
" print(preview_df(clinical_features))\n",
" \n",
" # Save the clinical data\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 data saved to {out_clinical_data_file}\")\n",
" \n",
" # 3. Link clinical and genetic data\n",
" linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
" print(f\"Linked data shape: {linked_data.shape}\")\n",
" print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
" print(linked_data.iloc[:5, :5] if linked_data.shape[0] > 0 and linked_data.shape[1] > 5 else linked_data)\n",
" \n",
" # 4. Handle missing values\n",
" linked_data_clean = handle_missing_values(linked_data, trait)\n",
" print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n",
" \n",
" # 5. Check for bias in the dataset\n",
" is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n",
" \n",
" # 6. Conduct final quality validation\n",
" note = \"Dataset contains gene expression data from liver samples studying ischemia-reperfusion injury in patients with various liver diseases.\"\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_clean,\n",
" note=note\n",
" )\n",
" \n",
" # 7. Save the linked data if it's usable\n",
" if is_usable:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" linked_data_clean.to_csv(out_data_file, index=True)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
" else:\n",
" print(\"Dataset deemed not usable for associative studies. Linked data not saved.\")\n",
" \n",
"except Exception as e:\n",
" print(f\"Error processing clinical data: {e}\")\n",
" # If clinical processing fails, we should still validate the dataset status\n",
" is_usable = validate_and_save_cohort_info(\n",
" is_final=True,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=True,\n",
" is_trait_available=False, # Mark as false since we couldn't process it\n",
" is_biased=True, # Set to True to ensure it's not marked usable\n",
" df=pd.DataFrame(), # Empty dataframe since processing failed\n",
" note=\"Failed to process clinical data due to structural issues with the dataset.\"\n",
" )\n",
" print(\"Dataset validation completed with error status.\")"
]
}
],
"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
}
|