File size: 31,038 Bytes
82732bd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "2d90e327",
"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 = \"Sarcoma\"\n",
"cohort = \"GSE159848\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Sarcoma\"\n",
"in_cohort_dir = \"../../input/GEO/Sarcoma/GSE159848\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Sarcoma/GSE159848.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Sarcoma/gene_data/GSE159848.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Sarcoma/clinical_data/GSE159848.csv\"\n",
"json_path = \"../../output/preprocess/Sarcoma/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "cfb958f5",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ad0dbf1d",
"metadata": {},
"outputs": [],
"source": [
"# 1. Check what files are actually in the directory\n",
"import os\n",
"print(\"Files in the directory:\")\n",
"files = os.listdir(in_cohort_dir)\n",
"print(files)\n",
"\n",
"# 2. Find appropriate files with more flexible pattern matching\n",
"soft_file = None\n",
"matrix_file = None\n",
"\n",
"for file in files:\n",
" file_path = os.path.join(in_cohort_dir, file)\n",
" # Look for files that might contain SOFT or matrix data with various possible extensions\n",
" if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n",
" soft_file = file_path\n",
" if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n",
" matrix_file = file_path\n",
"\n",
"if not soft_file:\n",
" print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n",
" gz_files = [f for f in files if f.endswith('.gz')]\n",
" if gz_files:\n",
" soft_file = os.path.join(in_cohort_dir, gz_files[0])\n",
"\n",
"if not matrix_file:\n",
" print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n",
" gz_files = [f for f in files if f.endswith('.gz')]\n",
" if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n",
" matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n",
" elif len(gz_files) == 1 and not soft_file:\n",
" matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n",
"\n",
"print(f\"SOFT file: {soft_file}\")\n",
"print(f\"Matrix file: {matrix_file}\")\n",
"\n",
"# 3. Read files if found\n",
"if soft_file and matrix_file:\n",
" # 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",
" \n",
" try:\n",
" background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
" \n",
" # Obtain the sample characteristics dictionary from the clinical dataframe\n",
" sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
" \n",
" # 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",
" except Exception as e:\n",
" print(f\"Error processing files: {e}\")\n",
" # Try swapping files if first attempt fails\n",
" print(\"Trying to swap SOFT and matrix files...\")\n",
" temp = soft_file\n",
" soft_file = matrix_file\n",
" matrix_file = temp\n",
" try:\n",
" background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
" sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
" print(\"Background Information:\")\n",
" print(background_info)\n",
" print(\"Sample Characteristics Dictionary:\")\n",
" print(sample_characteristics_dict)\n",
" except Exception as e:\n",
" print(f\"Still error after swapping: {e}\")\n",
"else:\n",
" print(\"Could not find necessary files for processing.\")\n"
]
},
{
"cell_type": "markdown",
"id": "4ec756da",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a2f1321",
"metadata": {},
"outputs": [],
"source": [
"```python\n",
"import pandas as pd\n",
"import os\n",
"import json\n",
"from typing import Optional, Callable, Dict, Any\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# Based on the series description and overall design, this dataset contains gene expression data from microarray\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"\n",
"# For trait (sarcoma):\n",
"# Looking at the sample characteristics, all samples are mixoid liposarcoma patients (row 2)\n",
"# Since all samples are sarcoma patients, we need a binary trait for case-control analysis\n",
"# We'll use the metastasis status (row 3) as our trait of interest since it has binary values (0, 1)\n",
"trait_row = 3\n",
"\n",
"# For age:\n",
"# Age is available in row 1\n",
"age_row = 1\n",
"\n",
"# For gender:\n",
"# Gender (Sex) is available in row 0\n",
"gender_row = 0\n",
"\n",
"# 2.2 Data Type Conversion\n",
"\n",
"def convert_trait(value: str) -> Optional[int]:\n",
" \"\"\"Convert metastasis status to binary.\"\"\"\n",
" if value is None:\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 int(value) # 0 for no metastasis, 1 for metastasis\n",
" except (ValueError, TypeError):\n",
" return None\n",
"\n",
"def convert_age(value: str) -> Optional[float]:\n",
" \"\"\"Convert age to continuous numeric value.\"\"\"\n",
" if value is None:\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, TypeError):\n",
" return None\n",
"\n",
"def convert_gender(value: str) -> Optional[int]:\n",
" \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n",
" if value is None:\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" \n",
" # Convert to lowercase for case-insensitive comparison\n",
" value = value.lower()\n",
" \n",
" if value == 'f' or value == 'female':\n",
" return 0\n",
" elif value == 'm' or value == 'male':\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Determine trait data availability\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Initial filtering and save metadata\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",
" # In previous step the clinical data was parsed and is available in memory\n",
" # We need to get it from the sample characteristics dictionary\n",
" # Convert the dictionary to a DataFrame\n",
" clinical_dict = {0: ['Sex: M', 'Sex: F'], \n",
" 1: ['age: 44', 'age: 67', 'age: 54', 'age: 82', 'age: 47', 'age: 32', 'age: 57', \n",
" 'age: 60', 'age: 51', 'age: 45', 'age: 38', 'age: 16', 'age: 52', 'age: 46', \n",
" 'age: 58', 'age: 20', 'age: 39', 'age: 43', 'age: 31', 'age: 71', 'age: 49', \n",
" 'age: 28', 'age: 29', 'age: 75', 'age: 74', 'age: 40', 'age: 59', 'age: 42', \n",
" 'age: 35', 'age: 33'], \n",
" 2: ['subject status/id: mixoid liposarcoma patient 1', 'subject status/id: mixoid liposarcoma patient 2', \n",
" 'subject status/id: mixoid liposarcoma patient 3', 'subject status/id: mixoid liposarcoma patient 4', \n",
" 'subject status/id: mixoid liposarcoma patient 5', 'subject status/id: mixoid liposarcoma patient 6', \n",
" 'subject status/id: mixoid liposarcoma patient 7', 'subject status/id: mixoid liposarcoma patient 8', \n",
" 'subject status/id: mixoid liposarcoma patient 9', 'subject status/id: mixoid liposarcoma patient 10', \n",
" 'subject status/id: mixoid liposarcoma patient 11', 'subject status/id: mixoid liposarcoma patient 12', \n",
" 'subject status/id: mixoid liposarcoma patient 13', 'subject status/id: mixoid liposarcoma patient 14', \n",
" 'subject status/id: mixoid liposarcoma patient 15', 'subject status/id: mixoid liposarcoma patient 16', \n",
" 'subject status/id: mixoid liposarcoma patient 17', 'subject status/id: mixoid liposarcoma patient 18', \n",
" 'subject status/id: mixoid liposarcoma patient 19', 'subject status/id: mixoid liposarcoma patient 20', \n",
" 'subject status/id: mixoid liposarcoma patient 21', 'subject status/id: mixoid liposarcoma patient 22', \n",
" 'subject status/id: mixoid liposarcoma patient 23', 'subject status/id: mixoid liposarcoma patient 24', \n",
" 'subject status/id: mixoid liposarcoma patient 25', 'subject status/id: mixoid liposarcoma patient 26', \n",
" 'subject status/id: mixoid liposarcoma patient 27', 'subject status/id: mixoid liposarcoma patient 28', \n",
" 'subject status/id: mixoid liposarcoma patient 29', 'subject status/id: mixoid liposarcoma patient 30'], \n",
" 3: ['metastasis: 0', 'metastasis: 1'], \n",
" 4: ['time_mfs: 9.78630136986301', 'time_mfs: 0.463013698630137', 'time_mfs: 13.9150684931507', \n",
" 'time_mfs: 7.37534246575343', 'time_mfs: 11.9095890410959', 'time_mfs: 8.65753424657534', \n",
" 'time_mfs: 8.10684931506849', 'time_mfs: 6.52054794520548', 'time_mfs: 7.06301369863014', \n",
" 'time_mfs: 4.65753424657534', 'time_mfs: 6.75068493150685', 'time_mfs: 1.29315068493151', \n",
" 'time_mfs: 4.33150684931507', 'time_mfs: 4.50958904109589', 'time_mfs: 2.83835616438356', \n",
" 'time_mfs: 3.41917808219178', 'time_mfs: 1.70684931506849', 'time_mfs: 0.687671232876712', \n",
" 'time_mfs: 0.520547945205479', 'time_mfs: 0.501369863013699', 'time_mfs: 0.476712328767123', \n",
" 'time_mfs: 0.591780821917808', 'time_mfs: 0.441095890410959', 'time_mfs: 0.180821917808219', \n",
" 'time_mfs: 0.0575342465753425', 'time_mfs: 0.747945205479452', 'time_mfs: 0.380821917808219\n"
]
},
{
"cell_type": "markdown",
"id": "6b5829df",
"metadata": {},
"source": [
"### Step 3: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1d433786",
"metadata": {},
"outputs": [],
"source": [
"\n",
"import os\n",
"import pandas as pd\n",
"import json\n",
"import numpy as np\n",
"import gzip\n",
"from typing import Dict, Any, Optional, Callable\n",
"\n",
"# Function to read gzipped matrix file\n",
"def read_gzipped_matrix(file_path):\n",
" with gzip.open(file_path, 'rt') as f:\n",
" lines = f.readlines()\n",
" return lines\n",
"\n",
"# Load the matrix file (handling gzipped version)\n",
"matrix_file = os.path.join(in_cohort_dir, f\"{cohort}_series_matrix.txt.gz\")\n",
"if os.path.exists(matrix_file):\n",
" # Read the gzipped file\n",
" lines = read_gzipped_matrix(matrix_file)\n",
" \n",
" # Extract metadata section and data section\n",
" metadata_lines = []\n",
" data_start_idx = None\n",
" for i, line in enumerate(lines):\n",
" if line.startswith('!series_matrix_table_begin'):\n",
" data_start_idx = i + 1\n",
" break\n",
" metadata_lines.append(line)\n",
" \n",
" # Extract sample characteristics\n",
" sample_char_lines = [line for line in metadata_lines if line.startswith('!Sample_characteristics_ch1')]\n",
" \n",
" if sample_char_lines:\n",
" # Parse sample characteristics into a dataframe\n",
" sample_chars = []\n",
" for line in sample_char_lines:\n",
" parts = line.strip().split('\\t')\n",
" sample_chars.append(parts[1:])\n",
" \n",
" clinical_data = pd.DataFrame(sample_chars)\n",
" \n",
" # Print unique values for each row to identify trait, age, and gender\n",
" print(\"Examining sample characteristics rows:\")\n",
" for i in range(len(clinical_data.index)):\n",
" unique_values = clinical_data.iloc[i].unique()\n",
" print(f\"Row {i} unique values: {unique_values}\")\n",
" \n",
" # Check if there's a gene expression data section\n",
" if data_start_idx is not None:\n",
" data_line = lines[data_start_idx].strip()\n",
" data_cols = data_line.split('\\t')\n",
" first_data_line = lines[data_start_idx + 1].strip().split('\\t')\n",
" \n",
" print(\"\\nFirst few data columns:\")\n",
" for i in range(min(5, len(data_cols))):\n",
" print(f\"{data_cols[i]}: {first_data_line[i] if i < len(first_data_line) else 'N/A'}\")\n",
"else:\n",
" print(f\"Matrix file {matrix_file} not found.\")\n",
" clinical_data = pd.DataFrame()\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# Check if there's data that looks like gene expression\n",
"is_gene_available = True if data_start_idx is not None else False\n",
"\n",
"# 2.1 Data Availability\n",
"# Based on the examination of the sample characteristics:\n",
"# Row 0: Sex information\n",
"# Row 1: Age information\n",
"# Row 3: Metastasis status (binary, can be used as the trait)\n",
"gender_row = 0 # Sex information\n",
"age_row = 1 # Age information\n",
"trait_row = 3 # Using metastasis status as the trait variable\n",
"\n",
"# Validate that these rows exist and contain useful data\n",
"if len(clinical_data.index) <= trait_row or len(clinical_data.iloc[trait_row].unique()) <= 1:\n",
" trait_row = None\n",
"if len(clinical_data.index) <= age_row or len(clinical_data.iloc[age_row].unique()) <= 1:\n",
" age_row = None\n",
"if len(clinical_data.index) <= gender_row or len(clinical_data.iloc[gender_row].unique()) <= 1:\n",
" gender_row = None\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"def convert_trait(value):\n",
" if value is None or 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",
" # Convert metastasis status to binary\n",
" value = value.strip('\"') # Remove quotes\n",
" try:\n",
" return int(value) # Already 0 or 1\n",
" except:\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" if value is None or 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",
" # Remove quotes\n",
" value = value.strip('\"')\n",
" \n",
" # Try to extract numeric age\n",
" import re\n",
" age_match = re.search(r'\\d+', value)\n",
" if age_match:\n",
" return float(age_match.group())\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" if value is None or 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",
" # Remove quotes\n",
" value = value.strip('\"')\n",
" \n",
" # Convert to binary (0: female, 1: male)\n",
" lower_value = value.lower()\n",
" if 'female' in lower_value or 'f' == lower_value:\n",
" return 0\n",
" elif 'male' in lower_value or 'm' == lower_value:\n",
" return 1\n",
" return None\n",
"\n",
"# 3. Save Metadata\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",
" selected_clinical_df = geo_select_clinical_features(\n",
" clinical_data, trait, trait_row, convert_trait,\n",
" age_row, convert_age if age_row is not None else None,\n",
" gender_row, convert_gender if gender_row is not None else None\n",
" )\n",
" \n",
" # Preview the selected clinical features\n",
" print(\"\\nPreview of selected clinical features:\")\n",
" print(preview_df(selected_clinical_df))\n",
" \n",
" # Save 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)\n",
" print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
"else:\n",
" print(\"No trait data available, skipping clinical feature extraction.\")\n"
]
},
{
"cell_type": "markdown",
"id": "1f2ef5c2",
"metadata": {},
"source": [
"### Step 4: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d86fca0d",
"metadata": {},
"outputs": [],
"source": [
"# 1. First get the path to the soft and matrix files\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Looking more carefully at the background information\n",
"# This is a SuperSeries which doesn't contain direct gene expression data\n",
"# Need to investigate the soft file to find the subseries\n",
"print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n",
"\n",
"# Open the SOFT file to try to identify subseries\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" subseries_lines = []\n",
" for i, line in enumerate(f):\n",
" if 'Series_relation' in line and 'SuperSeries of' in line:\n",
" subseries_lines.append(line.strip())\n",
" if i > 1000: # Limit search to first 1000 lines\n",
" break\n",
"\n",
"# Display the subseries found\n",
"if subseries_lines:\n",
" print(\"Found potential subseries references:\")\n",
" for line in subseries_lines:\n",
" print(line)\n",
"else:\n",
" print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n",
"\n",
"# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n",
"try:\n",
" gene_data = get_genetic_data(matrix_file)\n",
" print(\"\\nGene data extraction result:\")\n",
" print(\"Number of rows:\", len(gene_data))\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",
" print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n"
]
},
{
"cell_type": "markdown",
"id": "79892f51",
"metadata": {},
"source": [
"### Step 5: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "023b5c28",
"metadata": {},
"outputs": [],
"source": [
"# Based on the gene identifiers shown, these don't appear to be standard human gene symbols\n",
"# The identifiers (like A_23_P100001) look like Agilent microarray probe IDs\n",
"# These will need to be mapped to standard gene symbols for proper analysis\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "d00c871c",
"metadata": {},
"source": [
"### Step 6: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7a37d789",
"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. 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": "f50215fe",
"metadata": {},
"source": [
"### Step 7: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b541020b",
"metadata": {},
"outputs": [],
"source": [
"# 1. Determine which columns contain gene identifiers and gene symbols\n",
"# Looking at the gene annotation preview and gene expression data:\n",
"# - 'ID' in gene_annotation contains probe identifiers (e.g., A_23_P100001)\n",
"# - 'GENE_SYMBOL' contains human gene symbols (e.g., FAM174B)\n",
"\n",
"# 2. Extract the relevant columns for mapping\n",
"probe_id_col = 'ID'\n",
"gene_symbol_col = 'GENE_SYMBOL'\n",
"\n",
"gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n",
"print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
"print(\"First few rows of gene mapping:\")\n",
"print(gene_mapping.head())\n",
"\n",
"# 3. Apply gene mapping to convert from probe-level to gene-level expression\n",
"gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
"print(f\"Converted gene expression data shape: {gene_data.shape}\")\n",
"print(\"First few rows of gene expression data:\")\n",
"print(gene_data.head())\n",
"\n",
"# Normalize gene symbols\n",
"gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"Final gene expression data shape after normalization: {gene_data.shape}\")\n",
"print(\"First few rows after normalization:\")\n",
"print(gene_data.head())\n",
"\n",
"# Save the gene expression data\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"gene_data.to_csv(out_gene_data_file)\n",
"print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "1f2171f7",
"metadata": {},
"source": [
"### Step 8: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "91b1e76e",
"metadata": {},
"outputs": [],
"source": [
"# 1. First, we'll reload the clinical data that was processed in Step 3\n",
"# This contains the metastasis status, age, and gender information\n",
"clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n",
"print(f\"Loaded clinical data from Step 3, shape: {clinical_data.shape}\")\n",
"\n",
"# If the current clinical data is just the \"Sarcoma\" variable, let's recreate it\n",
"# based on the analysis we did in Step 3\n",
"if clinical_data.shape[0] == 1 and \"Sarcoma\" in clinical_data.index:\n",
" print(\"Recreating clinical data with metastasis, age, and gender...\")\n",
" \n",
" # Get the matrix file to extract the sample characteristics data\n",
" soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
" \n",
" # Get background info and clinical data from the matrix file\n",
" background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
" clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
" background_info, clinical_raw = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
" \n",
" # Define the conversion functions from Step 3\n",
" def convert_trait(value):\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" value = value.strip('\"')\n",
" try:\n",
" return int(value) # Already 0 or 1\n",
" except:\n",
" return None\n",
"\n",
" def convert_age(value):\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" value = value.strip('\"')\n",
" import re\n",
" age_match = re.search(r'\\d+', value)\n",
" if age_match:\n",
" return float(age_match.group())\n",
" return None\n",
"\n",
" def convert_gender(value):\n",
" if value is None or pd.isna(value):\n",
" return None\n",
" if ':' in value:\n",
" value = value.split(':', 1)[1].strip()\n",
" value = value.strip('\"')\n",
" lower_value = value.lower()\n",
" if 'female' in lower_value or 'f' == lower_value:\n",
" return 0\n",
" elif 'male' in lower_value or 'm' == lower_value:\n",
" return 1\n",
" return None\n",
" \n",
" # Extract clinical features using the row indices identified in Step 3\n",
" trait_row = 3 # Metastasis status\n",
" age_row = 1 # Age information\n",
" gender_row = 0 # Sex information\n",
" \n",
" # Use \"Metastasis\" as the trait name since we're using metastasis status\n",
" trait_name = \"Metastasis\"\n",
" \n",
" clinical_data = geo_select_clinical_features(\n",
" clinical_raw, trait_name, trait_row, convert_trait,\n",
" age_row, convert_age, gender_row, convert_gender\n",
" )\n",
" \n",
" # Save the updated clinical data\n",
" clinical_data.to_csv(out_clinical_data_file)\n",
" print(f\"Updated clinical data saved to {out_clinical_data_file}\")\n",
" print(\"Clinical data sample:\")\n",
" print(preview_df(clinical_data))\n",
"\n",
"print(f\"Clinical data shape: {clinical_data.shape}\")\n",
"\n",
"# 2. Load the gene expression data\n",
"gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
"print(f\"Loaded gene expression data shape: {gene_data.shape}\")\n",
"\n",
"# 3. Link clinical and genetic data\n",
"linked_data = geo_link_clinical_genetic_data(clinical_data, gene_data)\n",
"print(f\"Shape of linked data: {linked_data.shape}\")\n",
"print(\"Linked data sample (first 5 rows, 5 columns):\")\n",
"print(linked_data.iloc[:5, :5])\n",
"\n",
"# 4. Handle missing values in the linked data\n",
"# The trait variable is \"Metastasis\" (not \"Sarcoma\")\n",
"trait_name = \"Metastasis\" if \"Metastasis\" in linked_data.columns else clinical_data.index[0]\n",
"linked_data_cleaned = handle_missing_values(linked_data, trait_name)\n",
"print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n",
"\n",
"# 5. Check if the trait and demographic features are biased\n",
"is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait_name)\n",
"\n",
"# 6. Validate the dataset and save cohort information\n",
"note = \"Dataset contains expression data for myxoid liposarcoma patients. Metastasis status (0=no metastasis, 1=metastasis) is used as the trait variable for association studies.\"\n",
"is_usable = validate_and_save_cohort_info(\n",
" is_final=True,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=True,\n",
" is_trait_available=True,\n",
" is_biased=is_trait_biased,\n",
" df=unbiased_linked_data,\n",
" note=note\n",
")\n",
"\n",
"# 7. Save the linked data if it's usable\n",
"if is_usable:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" unbiased_linked_data.to_csv(out_data_file)\n",
" print(f\"Saved processed linked data to {out_data_file}\")\n",
"else:\n",
" print(\"Dataset validation failed. Final linked data not saved.\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|