File size: 34,048 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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "1a92f989",
"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 = \"Intellectual_Disability\"\n",
"cohort = \"GSE59630\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Intellectual_Disability\"\n",
"in_cohort_dir = \"../../input/GEO/Intellectual_Disability/GSE59630\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Intellectual_Disability/GSE59630.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Intellectual_Disability/gene_data/GSE59630.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Intellectual_Disability/clinical_data/GSE59630.csv\"\n",
"json_path = \"../../output/preprocess/Intellectual_Disability/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "5fb2da15",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a2dc6449",
"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": "f504da40",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2181a652",
"metadata": {},
"outputs": [],
"source": [
"```python\n",
"# 1. Check gene expression data availability\n",
"# This dataset is about gene expression in the brain, as mentioned in the background information\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable availability and data type conversion\n",
"# 2.1 Data Availability\n",
"\n",
"# Intellectual Disability is represented as Down Syndrome (DS) in this dataset\n",
"# Found in key 2: 'disease status: CTL', 'disease status: DS'\n",
"trait_row = 2 \n",
"\n",
"# Age information is in key 4\n",
"age_row = 4 \n",
"\n",
"# Gender information is in key 3: 'Sex: F', 'Sex: M'\n",
"gender_row = 3 \n",
"\n",
"# 2.2 Data Type Conversion\n",
"def convert_trait(value):\n",
" \"\"\"Convert trait value (Down Syndrome status) to binary (0 for control, 1 for DS)\"\"\"\n",
" if value is None:\n",
" return None\n",
" # Extract the value after colon and strip whitespace\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if value.upper() == 'DS':\n",
" return 1\n",
" elif value.upper() == 'CTL':\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age to a numeric value in years\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" # Extract the value after colon and strip whitespace\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Extract numeric part and unit\n",
" import re\n",
" match = re.match(r'(\\d+)(\\w+)', value)\n",
" if not match:\n",
" return None\n",
" \n",
" number, unit = match.groups()\n",
" number = float(number)\n",
" \n",
" # Convert to years based on unit\n",
" if unit == 'yr':\n",
" return number\n",
" elif unit == 'mo':\n",
" return number / 12\n",
" elif unit == 'wg': # weeks of gestation\n",
" return number / 52 # approximate conversion to years\n",
" \n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" # Extract the value after colon and strip whitespace\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if value.upper() == 'F':\n",
" return 0\n",
" elif value.upper() == 'M':\n",
" return 1\n",
" \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",
"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 (if trait_row is not None)\n",
"if trait_row is not None:\n",
" # Create a DataFrame from the sample characteristics dictionary\n",
" sample_chars = {\n",
" 0: ['braincode: 97-DFC', 'braincode: 100-DFC', 'braincode: 100-V1C', 'braincode: 159-V1C', 'braincode: 132-DFC', 'braincode: 132-V1C', 'braincode: 132-CBC', 'braincode: 131-OFC', 'braincode: 131-DFC', 'braincode: 131-VFC', 'braincode: 131-ITC', 'braincode: 131-V1C', 'braincode: 131-HIP', 'braincode: 131-CBC', 'braincode: 171-DFC', 'braincode: 171-VFC', 'braincode: 171-MFC', 'braincode: 171-OFC', 'braincode: 171-S1C', 'braincode: 171-IPC', 'braincode: 171-STC', 'braincode: 171-ITC', 'braincode: 171-V1C', 'braincode: 171-CBC', 'braincode: 122-V1C', 'braincode: 122-CBC', 'braincode: 143-OFC', 'braincode: 143-DFC', 'braincode: 173-VFC', 'braincode: 173-ITC'], \n",
" 1: ['region: DFC', 'region: V1C', 'region: CBC', 'region: OFC', 'region: VFC', 'region: ITC', 'region: HIP', 'region: MFC', 'region: S1C', 'region: IPC', 'region: STC', 'region: FC'], \n",
" 2: ['disease status: CTL', 'disease status: DS'], \n",
" 3: ['Sex: F', 'Sex: M'], \n",
" 4: ['age: 17wg', 'age: 19wg', 'age: 22wg', 'age: 4mo', 'age: 6mo', 'age: 10mo', 'age: 12mo', 'age: 2yr', 'age: 3yr', 'age: 8yr', 'age: 15yr', 'age: 18yr', 'age: 22yr', 'age: 30yr', 'age: 42yr', 'age: 16wg', 'age: 1mo', 'age: 9mo', 'age: 14mo', 'age: 10yr', 'age: 13yr', 'age: 19yr', 'age: 39yr', 'age: 40yr'], \n",
" 5: ['Stage: 5', 'Stage: 6', 'Stage: 8', 'Stage: 9', 'Stage: 10', 'Stage: 11', 'Stage: 12', 'Stage: 13', 'Stage: 14'], \n",
" 6: ['postmortem interval: 2', 'postmortem interval: 4', 'postmortem interval: 1', 'postmortem interval: 22', 'postmortem interval: 26', 'postmortem interval: 18', 'postmortem interval: 12', 'postmortem interval: 8', 'postmortem interval: 16', 'postmortem interval: 14.5', 'postmortem interval: 28', 'postmortem interval: 9.5', 'postmortem interval: 19', 'postmortem interval: 3', 'postmortem interval: 23', 'postmortem interval: 24', 'postmortem interval: 11', 'postmortem interval: 17', 'postmortem interval: 15', 'postmortem interval: 10'], \n",
" 7: ['race: CC', 'race: AA', 'race: H'], \n",
" 8: ['rna integrity number: 8.9', 'rna integrity number: 10', 'rna integrity number: 7.6', 'rna integrity number: 9.5', 'rna integrity number: 9.2', 'rna integrity number: 7', 'rna integrity number: 7.1', 'rna integrity number: 7.5', 'rna integrity number: 7.4', 'rna integrity number: 8.4', 'rna integrity number: 8.6', 'rna integrity number: 8.8', 'rna integrity number: 8.7', 'rna integrity number: 9.4', 'rna integrity number: 9', 'rna integrity number: 9.6', 'rna integrity number: 9.8', 'rna integrity number: 5', 'rna integrity number: 7.2', 'rna integrity number: 8', 'rna integrity number: 7.8', 'rna integrity number: 9.7', 'rna integrity number: 8.1', 'rna integrity number: 7.9', 'rna integrity number: 9.3', '\n"
]
},
{
"cell_type": "markdown",
"id": "78589f2a",
"metadata": {},
"source": [
"### Step 3: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9648663a",
"metadata": {},
"outputs": [],
"source": [
"```python\n",
"import pandas as pd\n",
"import json\n",
"import os\n",
"import re\n",
"from typing import Optional, Callable, Dict, Any, List\n",
"\n",
"# First, examine what files are available in the cohort directory\n",
"print(f\"Examining directory: {in_cohort_dir}\")\n",
"if os.path.exists(in_cohort_dir):\n",
" directory_contents = os.listdir(in_cohort_dir)\n",
" print(f\"Files in directory: {directory_contents}\")\n",
"else:\n",
" print(f\"Directory {in_cohort_dir} does not exist\")\n",
" directory_contents = []\n",
"\n",
"# Check for available data files\n",
"series_matrix_files = [f for f in directory_contents if \"series_matrix\" in f.lower()]\n",
"soft_files = [f for f in directory_contents if f.lower().endswith(\".soft\") or f.lower().endswith(\".soft.gz\")]\n",
"json_files = [f for f in directory_contents if f.lower().endswith(\".json\")]\n",
"\n",
"# Load clinical data from available files\n",
"clinical_data_dict = {}\n",
"sample_characteristics = {}\n",
"\n",
"# Try to load clinical data from different possible file formats\n",
"if json_files and any(\"clinical_data\" in f.lower() for f in json_files):\n",
" clinical_json = next(f for f in json_files if \"clinical_data\" in f.lower())\n",
" clinical_data_path = os.path.join(in_cohort_dir, clinical_json)\n",
" try:\n",
" with open(clinical_data_path, 'r') as f:\n",
" clinical_data_dict = json.load(f)\n",
" sample_characteristics = clinical_data_dict.get(\"sample_characteristics\", {})\n",
" print(f\"Loaded clinical data from {clinical_json}\")\n",
" except Exception as e:\n",
" print(f\"Error loading {clinical_json}: {str(e)}\")\n",
"elif series_matrix_files:\n",
" # We would need to parse series matrix file to extract clinical data\n",
" print(\"Series matrix files found but need additional parsing\")\n",
" # Placeholder for series matrix parsing\n",
" is_gene_available = True\n",
" is_trait_available = False\n",
"elif soft_files:\n",
" # We would need to parse soft file to extract clinical data\n",
" print(\"SOFT files found but need additional parsing\")\n",
" # Placeholder for SOFT file parsing\n",
" is_gene_available = True\n",
" is_trait_available = False\n",
"else:\n",
" print(\"No recognizable clinical data files found\")\n",
" is_gene_available = False\n",
" is_trait_available = False\n",
"\n",
"# If we have sample characteristics, analyze them\n",
"if sample_characteristics:\n",
" print(\"Sample characteristics keys:\")\n",
" for key in sample_characteristics.keys():\n",
" print(f\"Key {key}: {sample_characteristics[key]}\")\n",
"\n",
" # Determine if gene expression data is available\n",
" platform_id = clinical_data_dict.get(\"platform_id\", \"\")\n",
" title = clinical_data_dict.get(\"title\", \"\")\n",
" summary = clinical_data_dict.get(\"summary\", \"\")\n",
"\n",
" is_gene_available = True\n",
" if any(term in platform_id.lower() or term in title.lower() or term in summary.lower() \n",
" for term in [\"mirna\", \"methylation\", \"methyl\"]):\n",
" if not any(term in platform_id.lower() or term in title.lower() or term in summary.lower() \n",
" for term in [\"gene expression\", \"transcriptome\", \"mrna\"]):\n",
" is_gene_available = False\n",
"\n",
" # Identify the row in sample characteristics containing trait information\n",
" trait_row = None\n",
" age_row = None\n",
" gender_row = None\n",
"\n",
" # Check each key in sample characteristics for trait, age, and gender data\n",
" for key, values in sample_characteristics.items():\n",
" unique_values = set(values)\n",
" \n",
" # Check for intellectual disability information\n",
" if any(\"intellectual\" in str(v).lower() for v in unique_values) or \\\n",
" any(\"disability\" in str(v).lower() for v in unique_values) or \\\n",
" any(\"id\" in str(v).lower() and \"patient\" in str(v).lower() for v in unique_values) or \\\n",
" any(\"control\" in str(v).lower() for v in unique_values):\n",
" if len(unique_values) > 1: # Ensure it's not a constant feature\n",
" trait_row = int(key)\n",
" \n",
" # Check for age information\n",
" if any(\"age\" in str(v).lower() for v in unique_values):\n",
" if len(unique_values) > 1: # Ensure it's not a constant feature\n",
" age_row = int(key)\n",
" \n",
" # Check for gender information\n",
" if any(\"gender\" in str(v).lower() for v in unique_values) or \\\n",
" any(\"sex\" in str(v).lower() for v in unique_values) or \\\n",
" any(\"male\" in str(v).lower() for v in unique_values) or \\\n",
" any(\"female\" in str(v).lower() for v in unique_values):\n",
" if len(unique_values) > 1: # Ensure it's not a constant feature\n",
" gender_row = int(key)\n",
"\n",
" # Define conversion functions\n",
" def convert_trait(value):\n",
" \"\"\"Convert trait values to binary (0: control, 1: intellectual disability).\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" value_lower = str(value).lower()\n",
" \n",
" # Extract content after colon if present\n",
" if \":\" in value_lower:\n",
" value_lower = value_lower.split(\":\", 1)[1].strip()\n",
" \n",
" if any(term in value_lower for term in [\"patient\", \"case\", \"intellectual disability\", \"id patient\"]):\n",
" return 1\n",
" elif any(term in value_lower for term in [\"control\", \"healthy\", \"normal\"]):\n",
" return 0\n",
" \n",
" return None\n",
"\n",
" def convert_age(value):\n",
" \"\"\"Convert age values to continuous numeric values.\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" value_str = str(value)\n",
" \n",
" # Extract content after colon if present\n",
" if \":\" in value_str:\n",
" value_str = value_str.split(\":\", 1)[1].strip()\n",
" \n",
" # Try to extract numeric age using regex\n",
" age_match = re.search(r'(\\d+(?:\\.\\d+)?)', value_str)\n",
" if age_match:\n",
" return float(age_match.group(1))\n",
" \n",
" return None\n",
"\n",
" def convert_gender(value):\n",
" \"\"\"Convert gender values to binary (0: female, 1: male).\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" value_lower = str(value).lower()\n",
" \n",
" # Extract content after colon if present\n",
" if \":\" in value_lower:\n",
" value_lower = value_lower.split(\":\", 1)[1].strip()\n",
" \n",
" if any(term in value_lower for term in [\"female\", \"f\", \"woman\"]):\n",
" return 0\n",
" elif any(term in value_lower for term in [\"male\", \"m\", \"man\"]):\n",
" return 1\n",
" \n",
" return None\n",
"\n",
" # Check trait data availability\n",
" is_trait_available = trait_row is not None\n",
"else:\n",
" # If no sample characteristics data is found, set variables to default values\n",
" trait_row = None\n",
" age_row = None\n",
" gender_row = None\n",
" is_trait_available = False\n",
"\n",
"# Print found information\n",
"print(f\"Gene expression data available: {is_gene_available}\")\n",
"print(f\"Trait data available: {is_trait_available}\")\n",
"if is_trait_available:\n",
" print(f\"Trait row: {trait_row}\")\n",
" print(f\"Age row: {age_row}\")\n",
" print(f\"Gender row: {gender_row}\")\n",
"\n",
"# Save metadata with 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 is_trait_available and sample_characteristics:\n",
" # Convert sample characteristics dictionary to DataFrame for processing\n",
" clinical_df = pd.DataFrame.from_dict(sample_characteristics, orient='index')\n",
" \n",
" # Extract clinical features\n",
" selected_clinical_df = geo_select_clinical_features(\n",
" clinical_df=clinical_df,\n",
" trait=trait,\n",
" trait_row=trait_row,\n"
]
},
{
"cell_type": "markdown",
"id": "bb461be2",
"metadata": {},
"source": [
"### Step 4: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4a9ceeab",
"metadata": {},
"outputs": [],
"source": [
"# 1. Get the file paths for the SOFT file and matrix file\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Extract gene expression data from the matrix file\n",
"try:\n",
" print(\"Extracting gene data from matrix file:\")\n",
" gene_data = get_genetic_data(matrix_file)\n",
" if gene_data.empty:\n",
" print(\"Extracted gene expression data is empty\")\n",
" is_gene_available = False\n",
" else:\n",
" print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n",
" print(\"First 20 gene IDs:\")\n",
" print(gene_data.index[:20])\n",
" is_gene_available = True\n",
"except Exception as e:\n",
" print(f\"Error extracting gene data: {e}\")\n",
" print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n",
" is_gene_available = False\n",
"\n",
"print(f\"\\nGene expression data available: {is_gene_available}\")\n"
]
},
{
"cell_type": "markdown",
"id": "74cd122a",
"metadata": {},
"source": [
"### Step 5: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3403bd70",
"metadata": {},
"outputs": [],
"source": [
"# Examining the gene identifiers from the output\n",
"# These appear to be Affymetrix probe IDs, not standard human gene symbols\n",
"# These numeric IDs (2315554, 2315633, etc.) need to be mapped to gene symbols\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "18e572b2",
"metadata": {},
"source": [
"### Step 6: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "215ec1cc",
"metadata": {},
"outputs": [],
"source": [
"# 1. Extract gene annotation data from the SOFT file\n",
"print(\"Extracting gene annotation data from SOFT file...\")\n",
"try:\n",
" # Use the library function to extract gene annotation\n",
" gene_annotation = get_gene_annotation(soft_file)\n",
" print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n",
" \n",
" # Preview the annotation DataFrame\n",
" print(\"\\nGene annotation preview (first few rows):\")\n",
" print(preview_df(gene_annotation))\n",
" \n",
" # Show column names to help identify which columns we need for mapping\n",
" print(\"\\nColumn names in gene annotation data:\")\n",
" print(gene_annotation.columns.tolist())\n",
" \n",
" # Check for relevant mapping columns\n",
" if 'GB_ACC' in gene_annotation.columns:\n",
" print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n",
" # Count non-null values in GB_ACC column\n",
" non_null_count = gene_annotation['GB_ACC'].count()\n",
" print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n",
" \n",
" if 'SPOT_ID' in gene_annotation.columns:\n",
" print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n",
" print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n",
" \n",
"except Exception as e:\n",
" print(f\"Error processing gene annotation data: {e}\")\n",
" is_gene_available = False\n"
]
},
{
"cell_type": "markdown",
"id": "18dd18ce",
"metadata": {},
"source": [
"### Step 7: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "55ba939a",
"metadata": {},
"outputs": [],
"source": [
"# 1. Identifying mapping columns in the gene annotation data\n",
"print(\"Examining gene annotation data to identify mapping columns...\")\n",
"\n",
"# The 'ID' column in gene_annotation contains probe IDs matching the gene expression data indices\n",
"# The 'gene_assignment' column contains gene symbol information, but needs parsing\n",
"\n",
"# Examining the gene_assignment column\n",
"print(\"\\nExample gene_assignment values:\")\n",
"print(gene_annotation['gene_assignment'].head(3).tolist())\n",
"\n",
"# 2. Create a mapping dataframe with probe IDs and gene symbols\n",
"print(\"\\nCreating gene mapping dataframe...\")\n",
"\n",
"# Function to extract gene symbols from gene_assignment string\n",
"def extract_gene_symbols(assignment):\n",
" if isinstance(assignment, str) and assignment != '---':\n",
" # Extract gene symbols that appear after '//' (typically the second element after splitting by '//')\n",
" parts = assignment.split('//')\n",
" if len(parts) >= 2:\n",
" gene_symbol = parts[1].strip()\n",
" return gene_symbol\n",
" return None\n",
"\n",
"# Apply extraction to create mapping\n",
"gene_annotation['Gene'] = gene_annotation['gene_assignment'].apply(extract_gene_symbols)\n",
"\n",
"# Create mapping dataframe with ID and Gene columns\n",
"mapping_df = gene_annotation[['ID', 'Gene']].copy()\n",
"mapping_df = mapping_df.dropna() # Remove rows without gene symbols\n",
"print(f\"Created mapping with {len(mapping_df)} entries\")\n",
"print(\"\\nMapping preview:\")\n",
"print(mapping_df.head())\n",
"\n",
"# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n",
"print(\"\\nApplying gene mapping to convert probe measurements to gene expression...\")\n",
"\n",
"# Use the library function to map probes to genes\n",
"gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
"\n",
"print(f\"Converted data to {len(gene_data.index)} unique genes\")\n",
"print(\"\\nFirst few gene symbols:\")\n",
"print(gene_data.index[:10].tolist())\n",
"\n",
"# Print shape of resulting gene expression matrix\n",
"print(f\"\\nGene expression matrix shape: {gene_data.shape}\")\n"
]
},
{
"cell_type": "markdown",
"id": "c35bcce0",
"metadata": {},
"source": [
"### Step 8: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ce2e939c",
"metadata": {},
"outputs": [],
"source": [
"# 1. Get gene mapping function from previous step\n",
"def extract_gene_symbols(assignment):\n",
" if isinstance(assignment, str) and assignment != '---':\n",
" # Extract gene symbols that appear after '//' (typically the second element after splitting by '//')\n",
" parts = assignment.split('//')\n",
" if len(parts) >= 2:\n",
" gene_symbol = parts[1].strip()\n",
" return gene_symbol\n",
" return None\n",
"\n",
"# 2. Get the file paths for the SOFT file and matrix file again\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 3. Retrieve and process gene data \n",
"print(\"Retrieving gene expression data...\")\n",
"gene_data_raw = get_genetic_data(matrix_file)\n",
"gene_annotation = get_gene_annotation(soft_file)\n",
"gene_annotation['Gene'] = gene_annotation['gene_assignment'].apply(lambda x: extract_gene_symbols(x))\n",
"mapping_df = gene_annotation[['ID', 'Gene']].copy().dropna()\n",
"gene_data = apply_gene_mapping(gene_data_raw, mapping_df)\n",
"print(f\"Retrieved gene expression data with shape: {gene_data.shape}\")\n",
"\n",
"# 4. Normalize gene symbols in the gene expression data\n",
"print(\"Normalizing gene symbols in the expression data...\")\n",
"try:\n",
" # Normalize gene symbols\n",
" normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
" \n",
" # Create directory if it doesn't exist\n",
" os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
" \n",
" # Save normalized gene data\n",
" normalized_gene_data.to_csv(out_gene_data_file)\n",
" print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
" print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n",
" is_gene_available = True\n",
"except Exception as e:\n",
" print(f\"Error normalizing gene data: {e}\")\n",
" is_gene_available = False\n",
"\n",
"# 5. Extract clinical data since it doesn't exist yet\n",
"print(\"\\nExtracting clinical data...\")\n",
"try:\n",
" # Since we haven't yet extracted clinical features, do it now\n",
" # First, read background information and clinical data from the matrix file\n",
" background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
" \n",
" # Define conversion functions for trait (Down Syndrome), age, and gender\n",
" def convert_trait(value):\n",
" \"\"\"Convert trait value (Down Syndrome status) to binary (0 for control, 1 for DS)\"\"\"\n",
" if value is None:\n",
" return None\n",
" # Extract the value after colon and strip whitespace\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if value.upper() == 'DS':\n",
" return 1\n",
" elif value.upper() == 'CTL':\n",
" return 0\n",
" return None\n",
"\n",
" def convert_age(value):\n",
" \"\"\"Convert age to a numeric value in years\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" # Extract the value after colon and strip whitespace\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Extract numeric part and unit\n",
" import re\n",
" match = re.match(r'(\\d+)(\\w+)', value)\n",
" if not match:\n",
" return None\n",
" \n",
" number, unit = match.groups()\n",
" number = float(number)\n",
" \n",
" # Convert to years based on unit\n",
" if unit == 'yr':\n",
" return number\n",
" elif unit == 'mo':\n",
" return number / 12\n",
" elif unit == 'wg': # weeks of gestation\n",
" return number / 52 # approximate conversion to years\n",
" \n",
" return None\n",
"\n",
" def convert_gender(value):\n",
" \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" # Extract the value after colon and strip whitespace\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" if value.upper() == 'F':\n",
" return 0\n",
" elif value.upper() == 'M':\n",
" return 1\n",
" \n",
" return None\n",
" \n",
" # Based on earlier inspection, we know:\n",
" # trait_row = 2 (disease status: CTL or DS)\n",
" # age_row = 4 (age: with various values)\n",
" # gender_row = 3 (Sex: F or M)\n",
" \n",
" # Extract clinical features\n",
" selected_clinical_df = geo_select_clinical_features(\n",
" clinical_data, \n",
" trait=trait, \n",
" trait_row=2, \n",
" convert_trait=convert_trait,\n",
" age_row=4, \n",
" convert_age=convert_age, \n",
" gender_row=3, \n",
" convert_gender=convert_gender\n",
" )\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 the clinical data\n",
" selected_clinical_df.to_csv(out_clinical_data_file)\n",
" print(f\"Clinical data extracted and saved to {out_clinical_data_file}\")\n",
" print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
" \n",
" is_trait_available = True\n",
"except Exception as e:\n",
" print(f\"Error extracting clinical data: {e}\")\n",
" selected_clinical_df = pd.DataFrame() # Empty dataframe instead of None\n",
" is_trait_available = False\n",
"\n",
"# 6. Link clinical and genetic data\n",
"print(\"\\nLinking clinical and genetic data...\")\n",
"try:\n",
" if is_trait_available and is_gene_available:\n",
" # Link clinical and genetic data\n",
" linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n",
" print(f\"Linked data shape: {linked_data.shape}\")\n",
" \n",
" # 7. Handle missing values systematically\n",
" print(\"\\nHandling missing values...\")\n",
" linked_data = handle_missing_values(linked_data, trait)\n",
" print(f\"After handling missing values, data shape: {linked_data.shape}\")\n",
" \n",
" # 8. Determine whether features are biased\n",
" print(\"\\nChecking for bias in features...\")\n",
" is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
" else:\n",
" print(\"Cannot link data: gene or trait data is not available\")\n",
" if is_trait_available:\n",
" linked_data = selected_clinical_df.T # Use clinical data if available\n",
" else:\n",
" linked_data = pd.DataFrame({trait: [0, 1]}) # Minimal dataframe for validation\n",
" is_biased = True\n",
"except Exception as e:\n",
" print(f\"Error in data linking or processing: {e}\")\n",
" linked_data = pd.DataFrame({trait: [0, 1]}) # Minimal dataframe for validation\n",
" is_biased = True\n",
"\n",
"# 9. Validate and save cohort info\n",
"print(\"\\nPerforming final validation...\")\n",
"is_usable = validate_and_save_cohort_info(\n",
" is_final=True,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=is_gene_available,\n",
" is_trait_available=is_trait_available,\n",
" is_biased=is_biased,\n",
" df=linked_data,\n",
" note=\"Down Syndrome dataset with gene expression from brain tissues across lifespan.\"\n",
")\n",
"\n",
"# 10. Save the linked data if usable\n",
"if is_usable:\n",
" # Create directory if it doesn't exist\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" \n",
" # Save linked data\n",
" linked_data.to_csv(out_data_file)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
"else:\n",
" print(f\"Dataset not usable for {trait} association studies. Data not saved.\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|