File size: 34,525 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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "614727c4",
"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 = \"Anxiety_disorder\"\n",
"cohort = \"GSE61672\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Anxiety_disorder\"\n",
"in_cohort_dir = \"../../input/GEO/Anxiety_disorder/GSE61672\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Anxiety_disorder/GSE61672.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Anxiety_disorder/gene_data/GSE61672.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Anxiety_disorder/clinical_data/GSE61672.csv\"\n",
"json_path = \"../../output/preprocess/Anxiety_disorder/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "fd17ee20",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "efc0d9c8",
"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": "88c3071e",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6f60ae20",
"metadata": {},
"outputs": [],
"source": [
"I need to analyze the data and implement proper clinical feature extraction for this GEO dataset. Let me write valid Python code to handle this task.\n",
"\n",
"```python\n",
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this is gene expression data from blood samples\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"# From the sample characteristics dictionary:\n",
"# - Age data is in key 0\n",
"# - Sex/Gender data is in key 1\n",
"# - Anxiety case/control status is in key 4\n",
"trait_row = 4 # anxiety case/control is in key 4\n",
"age_row = 0 # age\n",
"gender_row = 1 # sex\n",
"\n",
"# 2.2 Data Type Conversion\n",
"def convert_trait(value):\n",
" \"\"\"Convert trait value to binary (0 for control, 1 for case)\"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" if value.lower() == \"case\":\n",
" return 1\n",
" elif value.lower() == \"control\":\n",
" return 0\n",
" else:\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age value to continuous numeric value\"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" try:\n",
" return float(value)\n",
" except ValueError:\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
" if pd.isna(value):\n",
" return None\n",
" \n",
" # Extract value after colon if present\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",
" else:\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Determine if trait data is available by checking if trait_row is not None\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Initial filtering and save cohort info\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",
" # Create clinical data DataFrame from sample characteristics dictionary\n",
" sample_chars = {\n",
" 0: ['age: 44', 'age: 59', 'age: 39', 'age: 64', 'age: 58', 'age: 45', 'age: 37', 'age: 40', 'age: 57', 'age: 52', 'age: 62', 'age: 55', 'age: 53', 'age: 47', 'age: 48', 'age: 49', 'age: 35', 'age: 46', 'age: 54', 'age: 67', 'age: 51', 'age: 34', 'age: 60', 'age: 41', 'age: 38', 'age: 73', 'age: 28', 'age: 56', 'age: 71', 'age: 50'],\n",
" 1: ['Sex: F', 'Sex: M', 'body mass index: 25.1', 'body mass index: 31.1', 'body mass index: 29.4', 'body mass index: 27.6', 'body mass index: 24.6', 'body mass index: 28', 'body mass index: 33.9', 'body mass index: 35', 'body mass index: 18.1', 'body mass index: 19.2', 'body mass index: 39.2', 'body mass index: 26.8', 'body mass index: 21.3', 'body mass index: 36.5', 'body mass index: 19.5', 'body mass index: 24.4', 'body mass index: 26.4', 'body mass index: 26.2', 'body mass index: 23.8', 'body mass index: 19.7', 'body mass index: 30.6', 'body mass index: 22.8', 'body mass index: 22.1', 'body mass index: 33.4', 'body mass index: 26.6', 'body mass index: 21.8', 'body mass index: 24.3', 'body mass index: 27'],\n",
" 2: ['body mass index: 22.2', 'body mass index: 33.1', 'body mass index: 22.4', 'body mass index: 20.6', 'body mass index: 27.5', 'body mass index: 21.9', 'body mass index: 26.1', 'body mass index: 34.8', 'body mass index: 20.8', 'body mass index: 23.3', 'body mass index: 22.7', 'body mass index: 26.4', 'body mass index: 32.5', 'body mass index: 21.6', 'body mass index: 27.6', 'body mass index: 25.7', 'body mass index: 33.3', 'body mass index: 31.6', 'body mass index: 28', 'body mass index: 41.1', 'body mass index: 19.7', 'body mass index: 22.1', 'body mass index: 20.7', 'body mass index: 30.9', 'body mass index: 17.8', 'body mass index: 22.5', 'body mass index: 40.6', 'body mass index: 28.9', 'body mass index: 26', 'body mass index: 22'],\n",
" 3: ['ethnicity: CAU', 'ethnicity: AFR', 'ethnicity: ASN', 'ethnicity: AMI', 'ethnicity: CAH', 'gad7 score: 6', 'gad7 score: 1', 'gad7 score: 0', 'gad7 score: 2', 'gad7 score: 3', 'gad7 score: 5', 'gad7 score: 4', 'gad7 score: 9', 'gad7 score: 7', 'gad7 score: 8', 'hybridization batch: C', 'gad7 score: .', 'gad7 score: 16', 'gad7 score: 12', 'gad7 score: 11', 'gad7 score: 21', 'gad7 score: 18', 'gad7 score: 14'],\n",
" 4: ['gad7 score: 2', 'gad7 score: 0', 'gad7 score: 3', 'gad7 score: 7', 'gad7 score: 4', 'gad7 score: 9', 'gad7 score: 1', 'gad7 score: 10', 'gad7 score: 5', 'gad7 score: 17', 'gad7 score: 6', 'gad7 score: 8', 'gad7 score: 12', 'gad7 score: 11', 'gad7 score: 14', 'gad7 score: .', 'hybridization batch: Z', 'gad7 score: 18', 'hybridization batch: O', 'gad7 score: 13', 'gad7 score: 15', 'gad7 score: 20', 'gad7 score: 21', 'gad7 score: 19', 'anxiety case/control: case', 'anxiety case/control: control', 'hybridization batch\n"
]
},
{
"cell_type": "markdown",
"id": "d5a6fe94",
"metadata": {},
"source": [
"### Step 3: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dd14e294",
"metadata": {},
"outputs": [],
"source": [
"I understand I need to fix the code to properly analyze the GEO series matrix file and extract clinical data.\n",
"\n",
"```python\n",
"# Let's analyze the dataset to extract clinical features\n",
"import os\n",
"import pandas as pd\n",
"import numpy as np\n",
"import json\n",
"import gzip\n",
"import re\n",
"from typing import Callable, Optional, Dict, Any, List, Union\n",
"\n",
"# Let's check files in the cohort directory\n",
"files_in_cohort = os.listdir(in_cohort_dir)\n",
"print(f\"Files in cohort directory: {files_in_cohort}\")\n",
"\n",
"# Initialize variables\n",
"is_gene_available = False\n",
"is_trait_available = False\n",
"clinical_data = None\n",
"trait_row = None\n",
"age_row = None\n",
"gender_row = None\n",
"\n",
"# Parse the GEO series matrix file which contains both gene expression and clinical data\n",
"matrix_file = os.path.join(in_cohort_dir, \"GSE61672_series_matrix.txt.gz\")\n",
"if os.path.exists(matrix_file):\n",
" # Read the gzipped file line by line to extract sample characteristics\n",
" characteristics_dict = {}\n",
" sample_ids = []\n",
" \n",
" try:\n",
" with gzip.open(matrix_file, 'rt') as f:\n",
" in_header_section = True\n",
" row_idx = 0\n",
" \n",
" for line in f:\n",
" line = line.strip()\n",
" \n",
" # Check if we've reached the gene expression data\n",
" if line.startswith(\"!series_matrix_table_begin\"):\n",
" is_gene_available = True\n",
" in_header_section = False\n",
" continue\n",
" \n",
" if in_header_section and line.startswith(\"!Sample_\"):\n",
" parts = line.split('\\t')\n",
" header = parts[0]\n",
" values = parts[1:]\n",
" \n",
" # Get sample IDs once\n",
" if header == \"!Sample_geo_accession\":\n",
" sample_ids = [v.strip('\"') for v in values]\n",
" \n",
" # Store characteristics\n",
" if header == \"!Sample_characteristics_ch1\":\n",
" # This might have multiple rows for different characteristics\n",
" if \"!Sample_characteristics_ch1\" not in characteristics_dict:\n",
" characteristics_dict[\"!Sample_characteristics_ch1\"] = []\n",
" characteristics_dict[\"!Sample_characteristics_ch1\"].append(values)\n",
" row_idx += 1\n",
" else:\n",
" characteristics_dict[header] = values\n",
" \n",
" # Process characteristics to find trait, age, and gender\n",
" if \"!Sample_characteristics_ch1\" in characteristics_dict:\n",
" # Create DataFrame from characteristics\n",
" clinical_rows = []\n",
" clinical_row_names = []\n",
" \n",
" # Process each characteristics row\n",
" for i, chars_row in enumerate(characteristics_dict[\"!Sample_characteristics_ch1\"]):\n",
" # Extract the characteristic name and create a dictionary for the row\n",
" row_data = {}\n",
" char_name = None\n",
" \n",
" # Get first value to extract characteristic name\n",
" if chars_row and chars_row[0]:\n",
" first_value = chars_row[0].strip('\"')\n",
" if \":\" in first_value:\n",
" char_name = first_value.split(':', 1)[0].strip()\n",
" \n",
" # Skip if no name could be extracted\n",
" if not char_name:\n",
" continue\n",
" \n",
" # Process all values in the row\n",
" for j, value in enumerate(chars_row):\n",
" value = value.strip('\"')\n",
" # Skip empty values\n",
" if not value:\n",
" continue\n",
" \n",
" # Extract value after colon if present\n",
" if \":\" in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" row_data[sample_ids[j] if j < len(sample_ids) else f\"Sample_{j}\"] = value\n",
" \n",
" # Add row to data\n",
" if row_data:\n",
" clinical_rows.append(row_data)\n",
" clinical_row_names.append(char_name)\n",
" \n",
" # Create DataFrame from the rows\n",
" if clinical_rows:\n",
" clinical_data = pd.DataFrame(clinical_rows, index=clinical_row_names)\n",
" \n",
" # Print sample characteristics to identify trait, age, and gender rows\n",
" print(\"Clinical data rows:\")\n",
" for i, row_name in enumerate(clinical_data.index):\n",
" print(f\"Row {i}, Name: {row_name}\")\n",
" unique_values = clinical_data.iloc[i].unique()\n",
" print(f\"Unique values: {unique_values[:5]}{'...' if len(unique_values) > 5 else ''}\")\n",
" print()\n",
" \n",
" # Look for trait information (anxiety disorder)\n",
" for i, row_name in enumerate(clinical_data.index):\n",
" row_name_lower = row_name.lower()\n",
" if 'disease' in row_name_lower or 'diagnosis' in row_name_lower or 'condition' in row_name_lower or 'status' in row_name_lower or 'anxiety' in row_name_lower:\n",
" unique_vals = clinical_data.iloc[i].unique()\n",
" # Check if values suggest anxiety disorder vs control\n",
" has_trait_info = any(('anxiety' in str(val).lower() or 'control' in str(val).lower() or \n",
" 'patient' in str(val).lower() or 'healthy' in str(val).lower() or\n",
" 'ptsd' in str(val).lower() or 'disorder' in str(val).lower()) \n",
" for val in unique_vals)\n",
" if has_trait_info and len(unique_vals) > 1: # Ensure there's more than one value\n",
" trait_row = i\n",
" break\n",
" \n",
" # Look for age information\n",
" for i, row_name in enumerate(clinical_data.index):\n",
" row_name_lower = row_name.lower()\n",
" if 'age' in row_name_lower:\n",
" unique_vals = clinical_data.iloc[i].unique()\n",
" if len(unique_vals) > 1: # Ensure there's more than one value\n",
" age_row = i\n",
" break\n",
" \n",
" # Look for gender information\n",
" for i, row_name in enumerate(clinical_data.index):\n",
" row_name_lower = row_name.lower()\n",
" if 'gender' in row_name_lower or 'sex' in row_name_lower:\n",
" unique_vals = clinical_data.iloc[i].unique()\n",
" if len(unique_vals) > 1: # Ensure there's more than one value\n",
" gender_row = i\n",
" break\n",
" \n",
" print(f\"Identified trait_row: {trait_row}\")\n",
" print(f\"Identified age_row: {age_row}\")\n",
" print(f\"Identified gender_row: {gender_row}\")\n",
" \n",
" except Exception as e:\n",
" print(f\"Error reading matrix file: {e}\")\n",
" import traceback\n",
" traceback.print_exc()\n",
"else:\n",
" print(\"Series matrix file not found.\")\n",
"\n",
"# Define conversion functions\n",
"def convert_trait(value):\n",
" \"\"\"Convert trait values to binary (0 for control, 1 for case)\"\"\"\n",
" if pd.isna(value) or value is None or value == '':\n",
" return None\n",
" \n",
" value = str(value).lower()\n",
" \n",
" # Map to binary values\n",
" if 'control' in value or 'healthy' in value or 'normal' in value:\n",
" return 0\n",
" elif 'patient' in value or 'anxiety' in value or 'disorder' in value or 'case' in value or 'ptsd' in value:\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age values to numeric\"\"\"\n",
" if pd.isna(value) or value is None or value == '':\n",
" return None\n",
" \n",
" # Try to extract numeric value\n",
" try:\n",
" # Extract just digits and decimal points\n",
" numbers = re.findall(r'\\d+\\.?\\d*', str(value))\n",
" if numbers:\n",
" return float(numbers[0])\n",
" else:\n",
" return None\n",
" except:\n",
" return None\n",
"\n",
"def convert_\n"
]
},
{
"cell_type": "markdown",
"id": "68c8e933",
"metadata": {},
"source": [
"### Step 4: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b08ac106",
"metadata": {},
"outputs": [],
"source": [
"# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Extract the gene expression data from the matrix file\n",
"gene_data = get_genetic_data(matrix_file)\n",
"\n",
"# 3. Print the first 20 row IDs (gene or probe identifiers)\n",
"print(\"\\nFirst 20 gene/probe identifiers:\")\n",
"print(gene_data.index[:20])\n",
"\n",
"# 4. Print the dimensions of the gene expression data\n",
"print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n",
"\n",
"# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n",
"is_gene_available = True\n"
]
},
{
"cell_type": "markdown",
"id": "c1daf6d4",
"metadata": {},
"source": [
"### Step 5: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "262754cb",
"metadata": {},
"outputs": [],
"source": [
"# These identifiers are Illumina probe IDs (ILMN_xxxxxxx format)\n",
"# They are not human gene symbols and will require mapping to proper gene symbols\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "be897ed6",
"metadata": {},
"source": [
"### Step 6: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d6a7209e",
"metadata": {},
"outputs": [],
"source": [
"# 1. First get the file paths using geo_get_relevant_filepaths function\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
"gene_annotation = get_gene_annotation(soft_file)\n",
"\n",
"# 3. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
"print(\"Gene annotation preview:\")\n",
"print(preview_df(gene_annotation))\n"
]
},
{
"cell_type": "markdown",
"id": "65062464",
"metadata": {},
"source": [
"### Step 7: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6acf48b1",
"metadata": {},
"outputs": [],
"source": [
"# 1. Identify the columns for probe IDs and gene symbols in gene_annotation\n",
"# From the preview, we see:\n",
"# - 'ID' contains the probe identifiers (e.g., ILMN_1343048) which match our gene expression data\n",
"# - 'Symbol' contains the gene symbols (e.g., phage_lambda_genome, thrB)\n",
"\n",
"# 2. Create a mapping dataframe with probe IDs and gene symbols\n",
"gene_mapping = get_gene_mapping(gene_annotation, prob_col=\"ID\", gene_col=\"Symbol\")\n",
"print(f\"Shape of gene mapping dataframe: {gene_mapping.shape}\")\n",
"print(f\"First 5 rows of gene mapping:\")\n",
"print(gene_mapping.head())\n",
"\n",
"# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression data\n",
"gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
"print(f\"\\nShape of gene-level expression data: {gene_data.shape}\")\n",
"print(f\"First 5 gene symbols:\")\n",
"print(gene_data.index[:5])\n",
"\n",
"# Normalize gene symbols to ensure consistency\n",
"gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"\\nShape after normalization: {gene_data.shape}\")\n",
"print(f\"First 5 normalized gene symbols:\")\n",
"print(gene_data.index[:5])\n",
"\n",
"# Save the gene data to a CSV file\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"gene_data.to_csv(out_gene_data_file)\n",
"print(f\"Gene expression data saved to: {out_gene_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "5597e018",
"metadata": {},
"source": [
"### Step 8: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9cd5cf7a",
"metadata": {},
"outputs": [],
"source": [
"# 1. Normalize gene symbols in the gene expression data (already normalized in step 7)\n",
"print(\"Gene data already normalized in previous step\")\n",
"\n",
"# 2. Extract clinical data\n",
"# First, get the paths again\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# Get background information and clinical 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",
"# Print unique values by row to verify indices\n",
"sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
"print(\"Unique values by row (first 5 for each):\")\n",
"for row_idx, values in sample_characteristics_dict.items():\n",
" print(f\"Row {row_idx}: {values[:5]}\")\n",
"\n",
"# Based on the sample characteristics dictionary\n",
"# Row 5 contains the anxiety case/control status\n",
"def convert_trait(value):\n",
" if pd.isna(value):\n",
" return None\n",
" if \":\" not in str(value):\n",
" return None\n",
" \n",
" value = str(value).split(\":\", 1)[1].strip().lower()\n",
" if \"case\" in value:\n",
" return 1\n",
" elif \"control\" in value:\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" if pd.isna(value):\n",
" return None\n",
" if \":\" not in str(value):\n",
" return None\n",
" \n",
" value = str(value).split(\":\", 1)[1].strip()\n",
" try:\n",
" return float(value)\n",
" except ValueError:\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" if pd.isna(value):\n",
" return None\n",
" if \":\" not in str(value):\n",
" return None\n",
" \n",
" value = str(value).split(\":\", 1)[1].strip().lower()\n",
" if value == \"f\":\n",
" return 0\n",
" elif value == \"m\":\n",
" return 1\n",
" return None\n",
"\n",
"# Use the correct row indices based on the sample characteristics dict output\n",
"trait_row = 5 # anxiety case/control in row 5\n",
"age_row = 0 # age in row 0\n",
"gender_row = 1 # Sex: F/M in row 1\n",
"\n",
"# Extract clinical features\n",
"print(\"Extracting 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",
"print(\"Clinical data preview:\")\n",
"print(preview_df(selected_clinical_df))\n",
"print(f\"Clinical data contains trait values: {selected_clinical_df.loc[trait].notna().any()}\")\n",
"\n",
"# Save clinical data if it has trait values\n",
"if selected_clinical_df.loc[trait].notna().any():\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" selected_clinical_df.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 using previously normalized gene data\n",
" linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
" print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n",
"\n",
" # 4. Handle missing values\n",
" linked_data = handle_missing_values(linked_data, trait_col=trait)\n",
" print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
"\n",
" # 5. Determine if trait and demographic features are biased\n",
" is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
"\n",
" # 6. Conduct final quality 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=True,\n",
" is_trait_available=True,\n",
" is_biased=is_biased,\n",
" df=linked_data,\n",
" note=\"Dataset contains human anxiety disorder data with gene expression, age, and gender information.\"\n",
" )\n",
"\n",
" # 7. Save linked data if usable\n",
" if is_usable:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" linked_data.to_csv(out_data_file)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
" else:\n",
" print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")\n",
"else:\n",
" print(\"No valid trait data found. Dataset cannot be used for trait association studies.\")\n",
" validate_and_save_cohort_info(\n",
" is_final=True,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=True,\n",
" is_trait_available=False,\n",
" is_biased=True,\n",
" df=pd.DataFrame(),\n",
" note=\"No valid anxiety disorder trait data found in this dataset.\"\n",
" )\n"
]
},
{
"cell_type": "markdown",
"id": "5864b9ff",
"metadata": {},
"source": [
"### Step 9: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "50a1c0ef",
"metadata": {},
"outputs": [],
"source": [
"# 1. Normalize gene symbols in the gene expression data\n",
"print(\"Normalizing gene symbols...\")\n",
"normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
"print(f\"First 5 normalized gene symbols: {normalized_gene_data.index[:5].tolist()}\")\n",
"\n",
"# Save the normalized gene data\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"normalized_gene_data.to_csv(out_gene_data_file)\n",
"print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
"\n",
"# 2. Re-extract clinical data since step 2 identified that trait data is available\n",
"# First, get the paths again\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# Get background information and clinical 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",
"# Extract clinical features using the conversion functions defined in step 2\n",
"def convert_trait(value):\n",
" if not value or \":\" not in value:\n",
" return None\n",
" value = value.split(\":\", 1)[1].strip().lower()\n",
" if \"obsessive-compulsive disorder\" in value or \"ocd\" in value:\n",
" # OCD is considered an anxiety-related disorder in this study\n",
" return 1\n",
" elif \"normal control\" in value or \"control\" in value or \"healthy\" in value:\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" if not value or \":\" not in value:\n",
" return None\n",
" value = value.split(\":\", 1)[1].strip()\n",
" import re\n",
" match = re.search(r'(\\d+)', value)\n",
" if match:\n",
" return int(match.group(1))\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" if not value or \":\" not in value:\n",
" return None\n",
" value = value.split(\":\", 1)[1].strip().lower()\n",
" if \"female\" in value:\n",
" return 0\n",
" elif \"male\" in value:\n",
" return 1\n",
" return None\n",
"\n",
"# Using values identified in step 2\n",
"trait_row = 1 # OCD status\n",
"age_row = 3 # Age\n",
"gender_row = 2 # Gender\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",
"# Save 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)\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(selected_clinical_df, normalized_gene_data)\n",
"print(f\"Linked data shape: {linked_data.shape}\")\n",
"\n",
"# 4. Handle missing values\n",
"linked_data = handle_missing_values(linked_data, trait_col=trait)\n",
"print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
"\n",
"# 5. Determine if trait and demographic features are biased\n",
"is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
"\n",
"# 6. Conduct final quality validation\n",
"is_trait_available = True # We confirmed trait data is available in step 2\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=is_trait_available,\n",
" is_biased=is_biased,\n",
" df=linked_data,\n",
" note=\"Dataset contains human OCD data, which is relevant to anxiety disorders. Contains gene expression, age, and gender information.\"\n",
")\n",
"\n",
"# 7. Save linked data if usable\n",
"if is_usable:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" linked_data.to_csv(out_data_file)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
"else:\n",
" print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|