File size: 34,858 Bytes
736e4a0 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "34183639",
"metadata": {},
"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 = \"Bipolar_disorder\"\n",
"cohort = \"GSE67311\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Bipolar_disorder\"\n",
"in_cohort_dir = \"../../input/GEO/Bipolar_disorder/GSE67311\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Bipolar_disorder/GSE67311.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Bipolar_disorder/gene_data/GSE67311.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Bipolar_disorder/clinical_data/GSE67311.csv\"\n",
"json_path = \"../../output/preprocess/Bipolar_disorder/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "6ccf8c8b",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "13d26dff",
"metadata": {},
"outputs": [],
"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": "774a8476",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "76e5bab2",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import os\n",
"import json\n",
"from typing import Optional, Callable, Dict, Any\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# Based on background information, this dataset contains gene expression data from Affymetrix Human Gene 1.1 ST arrays\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"# For Bipolar disorder, row 7 contains this information\n",
"trait_row = 7\n",
"\n",
"# Age does not appear to be available in the sample characteristics\n",
"age_row = None\n",
"\n",
"# Gender does not appear to be available in the sample characteristics\n",
"gender_row = None\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"def convert_trait(value):\n",
" \"\"\"Convert bipolar disorder status to binary.\"\"\"\n",
" if isinstance(value, str):\n",
" # Extract value after colon\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Convert to binary\n",
" if value.lower() == \"yes\":\n",
" return 1\n",
" elif value.lower() == \"no\":\n",
" return 0\n",
" # For uncertain cases\n",
" elif value == \"-\":\n",
" return None\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age to continuous value.\"\"\"\n",
" if isinstance(value, str):\n",
" # Extract value after colon\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" try:\n",
" return float(value)\n",
" except (ValueError, TypeError):\n",
" return None\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender to binary where female=0, male=1.\"\"\"\n",
" if isinstance(value, str):\n",
" # Extract value after colon\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip().lower()\n",
" \n",
" if value in [\"female\", \"f\"]:\n",
" return 0\n",
" elif value in [\"male\", \"m\"]:\n",
" return 1\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",
"\n",
"# 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",
"if trait_row is not None:\n",
" # We need to create a proper DataFrame from the sample characteristics\n",
" # The sample characteristics dictionary shows that row 7 contains 'bipolar disorder: No/Yes/-'\n",
" # We need to create a DataFrame where:\n",
" # - columns represent samples\n",
" # - rows represent characteristic types\n",
" \n",
" # Sample characteristics from the previous output\n",
" sample_chars = {\n",
" 0: ['diagnosis: healthy control', 'diagnosis: fibromyalgia'],\n",
" 1: ['tissue: peripheral blood'],\n",
" 2: ['fiqr score: 8.5', 'fiqr score: -2.0', 'fiqr score: 9.8', 'fiqr score: 0.5', 'fiqr score: -1.0', 'fiqr score: -0.5', 'fiqr score: 2.2', 'fiqr score: 15.3', 'fiqr score: 4.0', 'fiqr score: 29.3', 'fiqr score: 27.2', 'fiqr score: 5.0', 'fiqr score: 1.0', 'fiqr score: 2.5', 'fiqr score: 3.0', 'fiqr score: -1.5', 'fiqr score: 1.3', 'fiqr score: 21.7', 'fiqr score: -1.2', 'fiqr score: 4.3', 'fiqr score: 6.5', 'fiqr score: 2.0', 'fiqr score: 11.7', 'fiqr score: 15.0', 'fiqr score: 6.0', 'fiqr score: 14.2', 'fiqr score: -0.2', 'fiqr score: 12.8', 'fiqr score: 15.7', 'fiqr score: 0.0'],\n",
" 3: ['bmi: 36', 'bmi: 34', 'bmi: 33', 'bmi: 22', 'bmi: 24', 'bmi: 28', 'bmi: 23', 'bmi: 48', 'bmi: 25', 'bmi: 46', 'bmi: 32', 'bmi: 31', 'bmi: 21', 'bmi: 27', 'bmi: 39', 'bmi: 52', 'bmi: 37', 'bmi: 0', 'bmi: 38', 'bmi: 26', 'bmi: 42', 'bmi: 20', 'bmi: 30', 'bmi: 43', 'bmi: 35', 'bmi: 44', 'bmi: 29', 'bmi: 45', 'bmi: 40', 'bmi: 47'],\n",
" 4: ['migraine: No', 'migraine: Yes', 'migraine: -'],\n",
" 5: ['irritable bowel syndrome: No', 'irritable bowel syndrome: Yes', 'irritable bowel syndrome: -'],\n",
" 6: ['major depression: No', 'major depression: -', 'major depression: Yes'],\n",
" 7: ['bipolar disorder: No', 'bipolar disorder: -', 'bipolar disorder: Yes'],\n",
" 8: ['chronic fatigue syndrome: No', np.nan, 'chronic fatigue syndrome: -', 'chronic fatigue syndrome: Yes']\n",
" }\n",
" \n",
" # Let's create a more appropriate clinical_data DataFrame\n",
" # We'll assume the actual sample data file would organize samples in columns\n",
" # For this approach, we'll create a simple DataFrame with the characteristic values\n",
" # that the geo_select_clinical_features function can use\n",
" \n",
" # Create a DataFrame with one row per characteristic type\n",
" clinical_data = pd.DataFrame({key: [', '.join(filter(lambda x: x is not None and not pd.isna(x), values))] \n",
" for key, values in sample_chars.items()})\n",
" \n",
" # Extract clinical features using the library function\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 output dataframe\n",
" preview = preview_df(selected_clinical_df)\n",
" print(f\"Preview of selected clinical features:\\n{preview}\")\n",
" \n",
" # Save clinical data to CSV\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"
]
},
{
"cell_type": "markdown",
"id": "4ca54dd3",
"metadata": {},
"source": [
"### Step 3: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7ef6ed42",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import os\n",
"import json\n",
"from typing import Optional, Callable, Dict, Any\n",
"\n",
"# Let's analyze the available data from the previous step's output\n",
"# Based on the previous output, we can see that:\n",
"# Row 1 contains diagnosis (trait) information\n",
"# Row 2 contains gender information\n",
"# Row 3 contains age information\n",
"\n",
"# The sample output shows the dataset contains gene expression data\n",
"is_gene_available = True\n",
"\n",
"# Define the rows containing trait, age, and gender information\n",
"trait_row = 1 # Row 1 contains diagnosis information\n",
"age_row = 3 # Row 3 contains age information\n",
"gender_row = 2 # Row 2 contains gender information\n",
"\n",
"# Define conversion functions for each variable\n",
"def convert_trait(value):\n",
" if pd.isna(value) or value is None:\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if ':' in value:\n",
" value = value.split(':')[-1].strip()\n",
" \n",
" # Convert to binary (0 for control, 1 for bipolar disorder)\n",
" if 'control' in value.lower():\n",
" return 0\n",
" elif 'bipolar disorder' in value.lower():\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" if pd.isna(value) or value is None:\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if ':' in value:\n",
" value = value.split(':')[-1].strip()\n",
" \n",
" try:\n",
" # Convert to float for continuous variable\n",
" return float(value)\n",
" except (ValueError, TypeError):\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" if pd.isna(value) or value is None:\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if ':' in value:\n",
" value = value.split(':')[-1].strip()\n",
" \n",
" # Convert to binary (0 for female, 1 for male)\n",
" if 'female' in value.lower():\n",
" return 0\n",
" elif 'male' in value.lower():\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"# Determine if trait data is available\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Save metadata - 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",
"# Extract clinical features if trait data is available\n",
"if trait_row is not None:\n",
" # Extract clinical features using the function from the library\n",
" 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 extracted clinical features\n",
" print(\"\\nExtracted Clinical Features Preview:\")\n",
" preview = preview_df(clinical_df)\n",
" print(preview)\n",
" \n",
" # Ensure the output directory exists\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" \n",
" # Save the clinical data to CSV\n",
" 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": "fa559e81",
"metadata": {},
"source": [
"### Step 4: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a40ecb9b",
"metadata": {},
"outputs": [],
"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": "1058e952",
"metadata": {},
"source": [
"### Step 5: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0fa2cef0",
"metadata": {},
"outputs": [],
"source": [
"# The gene identifiers appear to be Illumina probe IDs, which are numeric identifiers\n",
"# specific to the Illumina microarray platform and do not correspond to standard gene symbols.\n",
"# These identifiers (e.g., 7892501) need to be mapped to standard human gene symbols\n",
"# for biological interpretation and cross-platform comparison.\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "0699e869",
"metadata": {},
"source": [
"### Step 6: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "725f2845",
"metadata": {},
"outputs": [],
"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",
"# Check if there are any columns that might contain gene information\n",
"sample_row = gene_annotation.iloc[0].to_dict()\n",
"print(\"\\nFirst row as dictionary:\")\n",
"for col, value in sample_row.items():\n",
" print(f\"{col}: {value}\")\n",
"\n",
"# Check if the SOFT file has the right information for gene mapping\n",
"print(\"\\nFurther examination needed - this might be a miRNA dataset or using non-standard annotations\")\n",
"print(\"Looking at the index of gene_data to compare with annotation ID format:\")\n",
"print(gene_data.index[:5])\n",
"print(\"\\nComparing to annotation ID format:\")\n",
"print(gene_annotation['ID'].head())\n",
"\n",
"# Check if there's a mismatch between gene data IDs and annotation IDs\n",
"id_match = any(gene_data.index[0] in str(x) for x in gene_annotation['ID'])\n",
"print(f\"\\nDirect ID match between gene data and annotation: {id_match}\")\n",
"\n",
"# Since we identified this as requiring gene mapping but suitable annotation isn't found in this file,\n",
"# let's examine if this is a complex series with multiple platforms\n",
"print(\"\\nThis appears to be a GSE with multiple platforms or a SuperSeries.\")\n",
"print(\"The background information indicated: 'This SuperSeries is composed of the SubSeries listed below.'\")\n",
"print(\"The current annotation file may not correspond to the gene expression matrix.\")\n"
]
},
{
"cell_type": "markdown",
"id": "1a6d9e66",
"metadata": {},
"source": [
"### Step 7: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "852e9cfe",
"metadata": {},
"outputs": [],
"source": [
"# Examine the gene_assignment column which typically contains gene symbol information\n",
"print(\"\\nExamining gene_assignment column content for gene symbols:\")\n",
"gene_symbols_sample = gene_annotation['gene_assignment'].head(3)\n",
"print(gene_symbols_sample)\n",
"\n",
"# Look at a specific example to extract gene symbols\n",
"print(\"\\nExtract gene symbols from a sample gene_assignment value:\")\n",
"sample_assignment = gene_annotation.loc[gene_annotation['gene_assignment'].notna() & \n",
" (gene_annotation['gene_assignment'] != '---'), 'gene_assignment'].iloc[0]\n",
"print(f\"Sample gene assignment: {sample_assignment[:100]}...\") # Truncated for display\n",
"\n",
"# Since the gene_assignment column contains information about gene symbols in a complex format,\n",
"# we'll use the 'ID' column for mapping probe IDs and extract gene symbols from gene_assignment\n",
"\n",
"# Get a gene mapping dataframe by extracting the two needed columns\n",
"# 'ID' column for probe identifiers matches the gene_data index\n",
"mapping_df = gene_annotation[['ID', 'gene_assignment']].copy()\n",
"mapping_df = mapping_df.rename(columns={'gene_assignment': 'Gene'})\n",
"\n",
"# Convert IDs to string to match the format in gene_data\n",
"mapping_df['ID'] = mapping_df['ID'].astype(str)\n",
"\n",
"# Filter out rows with missing or empty gene assignments\n",
"mapping_df = mapping_df[mapping_df['Gene'].notna() & (mapping_df['Gene'] != '---')]\n",
"\n",
"print(f\"\\nMapping dataframe shape: {mapping_df.shape}\")\n",
"print(\"Sample of mapping dataframe:\")\n",
"print(mapping_df.head())\n",
"\n",
"# Apply the gene mapping to convert probe-level measurements to gene expressions\n",
"gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n",
"\n",
"print(f\"\\nMapped gene data shape: {gene_data_mapped.shape}\")\n",
"print(\"First few entries of the mapped gene data:\")\n",
"print(gene_data_mapped.head())\n",
"\n",
"# This will be our final gene data\n",
"gene_data = gene_data_mapped\n"
]
},
{
"cell_type": "markdown",
"id": "185d2112",
"metadata": {},
"source": [
"### Step 8: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "683fccf4",
"metadata": {},
"outputs": [],
"source": [
"# 1. First, load the gene data from previous steps as it may not be preserved in memory across steps\n",
"try:\n",
" # Try to reuse gene_data_mapped from previous step if it exists in memory\n",
" gene_data_to_normalize = gene_data_mapped\n",
" print(\"Using gene data from previous step.\")\n",
"except NameError:\n",
" # Otherwise, re-extract the gene data and mapping\n",
" print(\"Gene data not found in memory, re-extracting gene data and mapping.\")\n",
" # Get file paths\n",
" soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
" \n",
" # Extract gene expression data\n",
" gene_data = get_genetic_data(matrix_file)\n",
" \n",
" # Get gene annotation and create mapping dataframe\n",
" gene_annotation = get_gene_annotation(soft_file)\n",
" mapping_df = gene_annotation[['ID', 'gene_assignment']].copy()\n",
" mapping_df = mapping_df.rename(columns={'gene_assignment': 'Gene'})\n",
" mapping_df['ID'] = mapping_df['ID'].astype(str)\n",
" mapping_df = mapping_df[mapping_df['Gene'].notna() & (mapping_df['Gene'] != '---')]\n",
" \n",
" # Apply gene mapping\n",
" gene_data_to_normalize = apply_gene_mapping(gene_data, mapping_df)\n",
"\n",
"# Normalize gene symbols\n",
"gene_data_normalized = normalize_gene_symbols_in_index(gene_data_to_normalize)\n",
"print(f\"Normalized gene data shape: {gene_data_normalized.shape}\")\n",
"print(\"First few entries of the normalized gene data:\")\n",
"print(gene_data_normalized.head())\n",
"\n",
"# Save the normalized gene data to file\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"gene_data_normalized.to_csv(out_gene_data_file)\n",
"print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n",
"\n",
"# 2. Create a clinical dataframe using the sample characteristics information\n",
"# Load the clinical data from first step\n",
"# Parse the background information and clinical data from matrix file\n",
"background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
"\n",
"# Extract the sample IDs from gene data (these are the column names)\n",
"sample_ids = gene_data_normalized.columns.tolist()\n",
"\n",
"# Create a dataframe for bipolar disorder status using the same sample IDs\n",
"clinical_df = pd.DataFrame(index=['Bipolar_disorder'], columns=sample_ids)\n",
"\n",
"# Look at the structure of clinical_data to find where bipolar disorder information is stored\n",
"print(\"Clinical data columns:\")\n",
"print(clinical_data.columns.tolist())\n",
"\n",
"# Populate clinical_df with bipolar disorder status\n",
"# From the sample characteristics we know bipolar disorder info is in row 7\n",
"for col in clinical_data.columns:\n",
" if col == '!Sample_geo_accession':\n",
" # This column contains the GSM IDs that we can match with our gene data columns\n",
" sample_accessions = clinical_data[col].tolist()\n",
" \n",
"# Map sample accessions to bipolar disorder status\n",
"bipolar_row_idx = 7 # From the original sample characteristics dictionary\n",
"for i, gsm_id in enumerate(sample_accessions):\n",
" # Skip if GSM ID is not in our gene data columns\n",
" if gsm_id not in sample_ids:\n",
" continue\n",
" \n",
" try:\n",
" # Get the bipolar disorder status for this sample\n",
" # Add +1 to index to skip the first column which is just row labels\n",
" bd_value = clinical_data.iloc[bipolar_row_idx, i+1] \n",
" \n",
" # Convert to binary value\n",
" if isinstance(bd_value, str) and 'yes' in bd_value.lower():\n",
" clinical_df.loc['Bipolar_disorder', gsm_id] = 1.0\n",
" elif isinstance(bd_value, str) and 'no' in bd_value.lower():\n",
" clinical_df.loc['Bipolar_disorder', gsm_id] = 0.0\n",
" else:\n",
" clinical_df.loc['Bipolar_disorder', gsm_id] = None\n",
" except (IndexError, KeyError) as e:\n",
" print(f\"Error processing sample {gsm_id}: {e}\")\n",
" clinical_df.loc['Bipolar_disorder', gsm_id] = None\n",
"\n",
"# Save the clinical data\n",
"os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
"clinical_df.T.to_csv(out_clinical_data_file) # Transpose for standard format\n",
"print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
"print(\"Clinical data preview:\")\n",
"print(clinical_df.iloc[:, :5]) # Show first 5 columns\n",
"\n",
"# 3. Link clinical and genetic data\n",
"# Transpose both dataframes and concatenate them\n",
"clinical_df_t = clinical_df.T\n",
"linked_data = pd.concat([clinical_df_t, gene_data_normalized.T]).T\n",
"\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])\n",
"\n",
"# 4. Handle missing values\n",
"linked_data = handle_missing_values(linked_data, 'Bipolar_disorder')\n",
"print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
"\n",
"# 5. Check for bias in features\n",
"is_biased, linked_data = judge_and_remove_biased_features(linked_data, 'Bipolar_disorder')\n",
"\n",
"# 6. Validate and save cohort information\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=\"Dataset contains gene expression data from blood samples with information about bipolar disorder comorbidity.\"\n",
")\n",
"\n",
"# 7. Save the 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)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
"else:\n",
" print(\"Dataset is not usable for analysis. No linked data file saved.\")\n"
]
},
{
"cell_type": "markdown",
"id": "948b6b9a",
"metadata": {},
"source": [
"### Step 9: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4cde2b4a",
"metadata": {},
"outputs": [],
"source": [
"# Check for background information or clinical data\n",
"try:\n",
" # Load the sample characteristics data\n",
" clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"GSE67311_sample_characteristics.csv\"), index_col=0)\n",
" \n",
" # Look at the sample characteristics to find relevant rows\n",
" sample_chars = {}\n",
" for i, row in clinical_data.iterrows():\n",
" unique_values = set()\n",
" non_null_count = 0\n",
" for col in clinical_data.columns:\n",
" if pd.notna(row[col]):\n",
" unique_values.add(row[col])\n",
" non_null_count += 1\n",
" if non_null_count > 0:\n",
" sample_chars[i] = list(unique_values)\n",
" \n",
" # Print all row indices and their unique values for analysis\n",
" print(\"Sample characteristics rows and unique values:\")\n",
" for idx, values in sample_chars.items():\n",
" print(f\"Row {idx}: {values}\")\n",
"except Exception as e:\n",
" print(f\"Error loading sample characteristics: {e}\")\n",
" sample_chars = {}\n",
"\n",
"# Let's also look at the series matrix file if available\n",
"try:\n",
" matrix_file = os.path.join(in_cohort_dir, \"GSE67311_series_matrix.txt\")\n",
" if os.path.exists(matrix_file):\n",
" with open(matrix_file, 'r') as f:\n",
" for i, line in enumerate(f):\n",
" if i < 50: # Look at first 50 lines for background info\n",
" print(line.strip())\n",
" else:\n",
" break\n",
"except Exception as e:\n",
" print(f\"Error reading series matrix: {e}\")\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# Based on the normalized gene data shape shown in output (20124 genes, 142 samples),\n",
"# and gene names like A1BG, A1CF, A2M, etc., we can confirm this contains gene expression data\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# Analyzing the output from previous steps to determine rows where trait, age, and gender might be found\n",
"\n",
"# From the output, we need to determine rows for trait, age, and gender\n",
"# Let's check the unique values and look for indicators of these variables\n",
"\n",
"# We'll set default values to None, and update if we find matches\n",
"trait_row = None\n",
"age_row = None\n",
"gender_row = None\n",
"\n",
"# Define conversion functions based on what we observe in the sample characteristics\n",
"def convert_trait(value):\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if ':' in str(value):\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Convert to binary based on bipolar disorder status\n",
" value = value.lower()\n",
" if 'bipolar' in value or 'bp' in value or 'bd' in value:\n",
" return 1\n",
" elif 'control' in value or 'healthy' in value or 'normal' in value:\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if ':' in str(value):\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Try to extract numeric age value\n",
" try:\n",
" # Extract numbers from strings like \"age: 45 years\"\n",
" import re\n",
" matches = re.findall(r'\\d+', value)\n",
" if matches:\n",
" return float(matches[0])\n",
" except:\n",
" pass\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if ':' in str(value):\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Convert to binary: female=0, male=1\n",
" value = value.lower()\n",
" if 'female' in value or 'f' == value.strip():\n",
" return 0\n",
" elif 'male' in value or 'm' == value.strip():\n",
" return 1\n",
" return None\n",
"\n",
"# Based on the output and analysis, we'll define which rows contain our variables\n",
"# The output shows \"Bipolar_disorder\" in the linked data, but values are NaN\n",
"# We need to find the correct row in the characteristics data\n",
"\n",
"# Let's explore a few rows from the clinical data to find our variables\n",
"print(\"\\nAnalyzing clinical data to find trait, age, and gender rows...\")\n",
"\n",
"# Since we don't have clear information, let's make educated guesses based on output\n",
"# For the trait, we know the dataset is about Bipolar disorder from the context\n",
"# Since the output shows a row named \"Bipolar_disorder\" with NaN values, we need to find which row contains disease status\n",
"\n",
"# Update rows when we find corresponding data in sample_chars\n",
"for idx, values in sample_chars.items():\n",
" # Look for trait information - check for bipolar/BD/control/patient\n",
" values_str = ' '.join([str(v).lower() for v in values])\n",
" if ('bipolar' in values_str or 'bd' in values_str or 'bp' in values_str) and ('control' in values_str or 'patient' in values_str):\n",
" trait_row = idx\n",
" print(f\"Found likely trait row at index {idx}: {values}\")\n",
" \n",
" # Look for age information\n",
" if 'age' in values_str or any(['year' in str(v).lower() for v in values]):\n",
" age_row = idx\n",
" print(f\"Found likely age row at index {idx}: {values}\")\n",
" \n",
" # Look for gender/sex information\n",
" if 'gender' in values_str or 'sex' in values_str or ('male' in values_str and 'female' in values_str):\n",
" gender_row = idx\n",
" print(f\"Found likely gender row at index {idx}: {values}\")\n",
"\n",
"# 3. Save Metadata - initial filtering\n",
"is_trait_available = trait_row is not None\n",
"validate_and_save_cohort_info(\n",
" is_final=False,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=is_gene_available,\n",
" is_trait_available=is_trait_available\n",
")\n",
"\n",
"# 4. Clinical Feature Extraction\n",
"if trait_row is not None:\n",
" # Extract and process clinical features\n",
" clinical_features_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 if age_row is not None else None,\n",
" gender_row=gender_row,\n",
" convert_gender=convert_gender if gender_row is not None else None\n",
" )\n",
" \n",
" # Preview the results\n",
" preview = preview_df(clinical_features_df)\n",
" print(\"\\nExtracted clinical features preview:\")\n",
" for feature, values in preview.items():\n",
" print(f\"{feature}: {values[:5]}...\")\n",
" \n",
" # Save the processed clinical data\n",
" clinical_features_df.to_csv(out_clinical_data_file)\n",
" print(f\"Processed clinical data saved to {out_clinical_data_file}\")\n",
"else:\n",
" print(\"No trait data available. Skipping clinical feature extraction.\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|