File size: 32,053 Bytes
9fe78b4 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "fc9e2c8c",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:43:12.743629Z",
"iopub.status.busy": "2025-03-25T03:43:12.743522Z",
"iopub.status.idle": "2025-03-25T03:43:12.919675Z",
"shell.execute_reply": "2025-03-25T03:43:12.919298Z"
}
},
"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 = \"Psoriasis\"\n",
"cohort = \"GSE183134\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Psoriasis\"\n",
"in_cohort_dir = \"../../input/GEO/Psoriasis/GSE183134\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Psoriasis/GSE183134.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Psoriasis/gene_data/GSE183134.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Psoriasis/clinical_data/GSE183134.csv\"\n",
"json_path = \"../../output/preprocess/Psoriasis/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "53975da2",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "22e803eb",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:43:12.921238Z",
"iopub.status.busy": "2025-03-25T03:43:12.921076Z",
"iopub.status.idle": "2025-03-25T03:43:13.026969Z",
"shell.execute_reply": "2025-03-25T03:43:13.026605Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"Transcriptomic profiling of Pityriasis Rubra Pilaris (PRP) and Psoriasis\"\n",
"!Series_summary\t\"The microarray experiment was employed to evaluate the gene expressions in skin lesions of PRP and psoriasis.\"\n",
"!Series_overall_design\t\"To investigate the specific gene regulations, microarray profiling was performed on RNA extracted from paraffin embedded skin biopsy samples.\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['tissue: Skin'], 1: ['disease state: Pityriasis_Rubra_Pilaris', 'disease state: Psoriasis']}\n"
]
}
],
"source": [
"from tools.preprocess import *\n",
"# 1. Identify the paths to the SOFT file and the matrix file\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. Read the matrix file to obtain background information and sample characteristics data\n",
"background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
"clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
"background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
"\n",
"# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
"sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
"\n",
"# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
"print(\"Background Information:\")\n",
"print(background_info)\n",
"print(\"Sample Characteristics Dictionary:\")\n",
"print(sample_characteristics_dict)\n"
]
},
{
"cell_type": "markdown",
"id": "938c9e97",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "2857c024",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:43:13.028247Z",
"iopub.status.busy": "2025-03-25T03:43:13.028130Z",
"iopub.status.idle": "2025-03-25T03:43:13.036019Z",
"shell.execute_reply": "2025-03-25T03:43:13.035681Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Preview of selected clinical features:\n",
"{'GSM5551681': [0.0], 'GSM5551682': [0.0], 'GSM5551683': [0.0], 'GSM5551684': [0.0], 'GSM5551685': [0.0], 'GSM5551686': [0.0], 'GSM5551687': [0.0], 'GSM5551688': [0.0], 'GSM5551689': [0.0], 'GSM5551690': [0.0], 'GSM5551691': [0.0], 'GSM5551692': [0.0], 'GSM5551693': [0.0], 'GSM5551694': [1.0], 'GSM5551695': [1.0], 'GSM5551696': [1.0], 'GSM5551697': [1.0], 'GSM5551698': [1.0], 'GSM5551699': [1.0], 'GSM5551700': [1.0], 'GSM5551701': [1.0], 'GSM5551702': [1.0], 'GSM5551703': [1.0], 'GSM5551704': [1.0], 'GSM5551705': [1.0], 'GSM5551706': [1.0], 'GSM5551707': [1.0], 'GSM5551708': [1.0], 'GSM5551709': [1.0], 'GSM5551710': [1.0], 'GSM5551711': [1.0], 'GSM5551712': [1.0], 'GSM5551713': [1.0], 'GSM5551714': [1.0], 'GSM5551715': [1.0]}\n",
"Clinical data saved to ../../output/preprocess/Psoriasis/clinical_data/GSE183134.csv\n"
]
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this is a microarray profiling study,\n",
"# so it likely contains gene expression data\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"# Checking the Sample Characteristics Dictionary\n",
"# The trait data (disease state) is available in row 1\n",
"trait_row = 1\n",
"# No age information is available\n",
"age_row = None\n",
"# No gender information is available\n",
"gender_row = None\n",
"\n",
"# 2.2 Data Type Conversion\n",
"def convert_trait(value):\n",
" \"\"\"Convert trait value to binary format (0 for PRP, 1 for Psoriasis)\"\"\"\n",
" if value is None:\n",
" return None\n",
" # Extract the value part if it contains a colon\n",
" if \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" # Convert to binary (1 for Psoriasis, 0 for PRP)\n",
" if \"psoriasis\" in value.lower():\n",
" return 1\n",
" elif \"pityriasis_rubra_pilaris\" in value.lower() or \"prp\" in value.lower():\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"Convert age value to numeric format\"\"\"\n",
" # Not needed as age data is not available\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"Convert gender value to binary format (0 for female, 1 for male)\"\"\"\n",
" # Not needed as gender data is not available\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",
"# Initial validation\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 data is available, extract clinical features\n",
"if trait_row is not None:\n",
" # Assuming clinical_data is already defined from previous step\n",
" selected_clinical_df = geo_select_clinical_features(\n",
" clinical_df=clinical_data,\n",
" trait=trait,\n",
" trait_row=trait_row,\n",
" convert_trait=convert_trait,\n",
" age_row=age_row,\n",
" convert_age=convert_age,\n",
" gender_row=gender_row,\n",
" convert_gender=convert_gender\n",
" )\n",
" \n",
" # Preview the dataframe\n",
" preview = preview_df(selected_clinical_df)\n",
" print(\"Preview of selected clinical features:\")\n",
" print(preview)\n",
" \n",
" # Save to CSV\n",
" selected_clinical_df.to_csv(out_clinical_data_file)\n",
" print(f\"Clinical data saved to {out_clinical_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "1a54da4e",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "ec02a445",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:43:13.037267Z",
"iopub.status.busy": "2025-03-25T03:43:13.037125Z",
"iopub.status.idle": "2025-03-25T03:43:13.169686Z",
"shell.execute_reply": "2025-03-25T03:43:13.169350Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"First 20 gene/probe identifiers:\n",
"Index(['1-Dec', '1-Sep', '10-Mar', '10-Sep', '11-Mar', '11-Sep', '12-Sep',\n",
" '14-Sep', '15-Sep', '2-Sep', '3-Mar', '3-Sep', '4-Mar', '4-Sep',\n",
" '5-Mar', '6-Mar', '6-Sep', '7-Mar', '7-Sep', '8-Mar'],\n",
" dtype='object', name='ID')\n",
"\n",
"Gene data dimensions: 29405 genes × 35 samples\n"
]
}
],
"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": "0bdb63da",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "24473946",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:43:13.170896Z",
"iopub.status.busy": "2025-03-25T03:43:13.170781Z",
"iopub.status.idle": "2025-03-25T03:43:13.172692Z",
"shell.execute_reply": "2025-03-25T03:43:13.172412Z"
}
},
"outputs": [],
"source": [
"# Examine the gene identifiers in the dataset\n",
"# The identifiers appear to be non-standard gene symbols (e.g., \"1-Dec\", \"1-Sep\", \"10-Mar\")\n",
"# These are likely probe identifiers or some other format that requires mapping to standard gene symbols\n",
"\n",
"# Based on biomedical knowledge, standard human gene symbols would follow HGNC nomenclature\n",
"# Examples of standard gene symbols: BRCA1, TP53, TNF, IL6, etc.\n",
"# The identifiers seen here (like \"1-Dec\", \"3-Mar\") don't conform to standard gene symbol conventions\n",
"\n",
"# These identifiers need to be mapped to standard gene symbols for proper analysis\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "c775aeb6",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "8366578d",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:43:13.173764Z",
"iopub.status.busy": "2025-03-25T03:43:13.173660Z",
"iopub.status.idle": "2025-03-25T03:43:14.332202Z",
"shell.execute_reply": "2025-03-25T03:43:14.331807Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Preview of SOFT file content:\n",
"^DATABASE = GeoMiame\n",
"!Database_name = Gene Expression Omnibus (GEO)\n",
"!Database_institute = NCBI NLM NIH\n",
"!Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n",
"!Database_email = [email protected]\n",
"^SERIES = GSE183134\n",
"!Series_title = Transcriptomic profiling of Pityriasis Rubra Pilaris (PRP) and Psoriasis\n",
"!Series_geo_accession = GSE183134\n",
"!Series_status = Public on Sep 30 2021\n",
"!Series_submission_date = Aug 31 2021\n",
"!Series_last_update_date = Jan 17 2022\n",
"!Series_pubmed_id = 34491907\n",
"!Series_summary = The microarray experiment was employed to evaluate the gene expressions in skin lesions of PRP and psoriasis.\n",
"!Series_overall_design = To investigate the specific gene regulations, microarray profiling was performed on RNA extracted from paraffin embedded skin biopsy samples.\n",
"!Series_type = Expression profiling by array\n",
"!Series_contributor = Johann,E,Gudjonsson\n",
"!Series_contributor = Lam,C,Tsoi\n",
"!Series_sample_id = GSM5551681\n",
"!Series_sample_id = GSM5551682\n",
"!Series_sample_id = GSM5551683\n",
"!Series_sample_id = GSM5551684\n",
"...\n",
"\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene annotation dataframe using default method:\n",
"Shape: (1058615, 2)\n",
"Columns: ['ID', 'SPOT_ID']\n",
" ID SPOT_ID\n",
"0 DDX11L1 DDX11L1\n",
"1 MIR1302-2 MIR1302-2\n",
"2 OR4F5 OR4F5\n",
"\n",
"Searching for platform annotation section in SOFT file...\n",
"^PLATFORM = GPL30572\n",
"!platform_table_begin\n",
"ID\tSPOT_ID\n",
"DDX11L1\tDDX11L1\n",
"MIR1302-2\tMIR1302-2\n",
"OR4F5\tOR4F5\n",
"LOC100132287\tLOC100132287\n",
"LOC105379690\tLOC105379690\n",
"OR4F29\tOR4F29\n",
"LOC105378947\tLOC105378947\n",
"LOC105378580\tLOC105378580\n",
"LOC100287934\tLOC100287934\n"
]
}
],
"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. Inspect the SOFT file structure to understand the annotation format\n",
"# Read the first few lines of the SOFT file to examine its structure\n",
"import gzip\n",
"print(\"Preview of SOFT file content:\")\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" for i, line in enumerate(f):\n",
" print(line.strip())\n",
" if i >= 20: # Print first 20 lines to understand structure\n",
" break\n",
"print(\"...\\n\")\n",
"\n",
"# 3. Try different approaches to extract gene annotation data\n",
"# First, let's try the default method to see what's actually in the file\n",
"gene_annotation = get_gene_annotation(soft_file)\n",
"print(\"Gene annotation dataframe using default method:\")\n",
"print(f\"Shape: {gene_annotation.shape}\")\n",
"print(f\"Columns: {gene_annotation.columns.tolist()}\")\n",
"print(gene_annotation.head(3))\n",
"\n",
"# 4. Check if there's another section in the file that might contain the mapping\n",
"# Look for platform annotation information in the SOFT file\n",
"print(\"\\nSearching for platform annotation section in SOFT file...\")\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" platform_lines = []\n",
" capture = False\n",
" for i, line in enumerate(f):\n",
" if \"^PLATFORM\" in line:\n",
" capture = True\n",
" platform_lines.append(line.strip())\n",
" elif capture and line.startswith(\"!platform_table_begin\"):\n",
" platform_lines.append(line.strip())\n",
" for j in range(10): # Capture the next 10 lines to understand the table structure\n",
" try:\n",
" platform_line = next(f).strip()\n",
" platform_lines.append(platform_line)\n",
" except StopIteration:\n",
" break\n",
" break\n",
" \n",
" print(\"\\n\".join(platform_lines))\n",
"\n",
"# Maintain gene availability status as True based on previous steps\n",
"is_gene_available = True\n"
]
},
{
"cell_type": "markdown",
"id": "4513f69c",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "b726b7ef",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:43:14.333515Z",
"iopub.status.busy": "2025-03-25T03:43:14.333386Z",
"iopub.status.idle": "2025-03-25T03:43:16.373895Z",
"shell.execute_reply": "2025-03-25T03:43:16.373428Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Platform annotation columns: ['ID', 'SPOT_ID']\n",
"First few rows of platform annotation:\n",
" ID SPOT_ID\n",
"0 DDX11L1 DDX11L1\n",
"1 MIR1302-2 MIR1302-2\n",
"2 OR4F5 OR4F5\n",
"3 LOC100132287 LOC100132287\n",
"4 LOC105379690 LOC105379690\n",
"Number of matching IDs between expression data and gene_annotation['ID']: 29405\n",
"Mapping dataframe shape: (1058580, 2)\n",
" ID Gene\n",
"0 DDX11L1 DDX11L1\n",
"1 MIR1302-2 MIR1302-2\n",
"2 OR4F5 OR4F5\n",
"3 LOC100132287 LOC100132287\n",
"4 LOC105379690 LOC105379690\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Mapped gene expression data shape: (22785, 35)\n",
"First few gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1']\n"
]
}
],
"source": [
"# 1. Examine both gene identifiers and annotation to determine mapping columns\n",
"# From previous steps, we can see:\n",
"# - The gene expression data has identifiers like \"1-Dec\", \"1-Sep\", \"10-Mar\" as index\n",
"# - The gene annotation data shows columns \"ID\" and \"SPOT_ID\"\n",
"\n",
"# Since the gene annotation DataFrame doesn't seem to contain our probe identifiers directly,\n",
"# we need to extract more detailed annotation from the SOFT file\n",
"\n",
"# Let's specifically look for the platform annotation that contains our probe IDs\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" platform_lines = []\n",
" capture = False\n",
" for line in f:\n",
" if \"!platform_table_begin\" in line:\n",
" capture = True\n",
" continue\n",
" elif \"!platform_table_end\" in line:\n",
" capture = False\n",
" break\n",
" elif capture:\n",
" platform_lines.append(line.strip())\n",
"\n",
"# Create a DataFrame from the platform lines if we found data\n",
"if platform_lines:\n",
" import io\n",
" platform_df = pd.read_csv(io.StringIO('\\n'.join(platform_lines)), sep='\\t')\n",
" print(f\"Platform annotation columns: {platform_df.columns.tolist()}\")\n",
" print(f\"First few rows of platform annotation:\")\n",
" print(platform_df.head())\n",
"else:\n",
" # If we couldn't find proper annotation, create a mapping from the gene expression data\n",
" # and annotation we already have\n",
" print(\"Could not find detailed probe-to-gene mapping in platform annotation.\")\n",
" # We'll proceed with the gene annotation we already extracted\n",
"\n",
"# 2. Get mapping between gene identifiers and gene symbols\n",
"# Based on the output from previous steps, both ID and SPOT_ID columns in gene_annotation\n",
"# appear to contain gene symbols. Let's check if either matches our expression data index\n",
"\n",
"# First, check if any IDs in gene_annotation match the expression data index\n",
"matching_ids = len(set(gene_data.index) & set(gene_annotation['ID']))\n",
"print(f\"Number of matching IDs between expression data and gene_annotation['ID']: {matching_ids}\")\n",
"\n",
"# If we didn't find matches, the gene identifiers might be in a different format\n",
"# Let's try to extract mapping from additional annotation or metadata\n",
"if matching_ids == 0:\n",
" print(\"No direct matches found. Creating alternative mapping...\")\n",
" \n",
" # For this dataset, it appears that the gene identifiers are non-standard, \n",
" # but the annotation provides standard gene symbols\n",
" # We'll create a simple 1:1 mapping using the annotation we have\n",
" \n",
" # Create a mapping dataframe where both probe ID and gene symbol are the same\n",
" # Since our gene identifiers don't seem to map directly to standard annotations,\n",
" # we'll use them as-is and treat them as approximations of gene symbols\n",
" mapping_df = pd.DataFrame({\n",
" 'ID': gene_data.index,\n",
" 'Gene': gene_data.index\n",
" })\n",
" \n",
" print(\"Created mapping with gene identifiers as gene symbols.\")\n",
" print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
" print(mapping_df.head())\n",
"else:\n",
" # If we found matching IDs, use them for mapping\n",
" mapping_df = gene_annotation[['ID', 'SPOT_ID']].rename(columns={'SPOT_ID': 'Gene'})\n",
" mapping_df = mapping_df[mapping_df['ID'].isin(gene_data.index)]\n",
" print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
" print(mapping_df.head())\n",
"\n",
"# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n",
"gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n",
"print(f\"Mapped gene expression data shape: {gene_data_mapped.shape}\")\n",
"print(f\"First few gene symbols: {list(gene_data_mapped.index[:5])}\")\n",
"\n",
"# Update gene_data to use the mapped values\n",
"gene_data = gene_data_mapped\n",
"\n",
"# Maintain gene availability status\n",
"is_gene_available = True\n"
]
},
{
"cell_type": "markdown",
"id": "eeafc1a6",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "99be8255",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:43:16.375375Z",
"iopub.status.busy": "2025-03-25T03:43:16.375261Z",
"iopub.status.idle": "2025-03-25T03:43:27.729245Z",
"shell.execute_reply": "2025-03-25T03:43:27.728882Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalizing gene symbols...\n",
"Gene data shape after normalization: 22464 genes × 35 samples\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalized gene expression data saved to ../../output/preprocess/Psoriasis/gene_data/GSE183134.csv\n",
"Extracting clinical features from the original source...\n",
"Extracted clinical features preview:\n",
"{'GSM5551681': [0.0], 'GSM5551682': [0.0], 'GSM5551683': [0.0], 'GSM5551684': [0.0], 'GSM5551685': [0.0], 'GSM5551686': [0.0], 'GSM5551687': [0.0], 'GSM5551688': [0.0], 'GSM5551689': [0.0], 'GSM5551690': [0.0], 'GSM5551691': [0.0], 'GSM5551692': [0.0], 'GSM5551693': [0.0], 'GSM5551694': [1.0], 'GSM5551695': [1.0], 'GSM5551696': [1.0], 'GSM5551697': [1.0], 'GSM5551698': [1.0], 'GSM5551699': [1.0], 'GSM5551700': [1.0], 'GSM5551701': [1.0], 'GSM5551702': [1.0], 'GSM5551703': [1.0], 'GSM5551704': [1.0], 'GSM5551705': [1.0], 'GSM5551706': [1.0], 'GSM5551707': [1.0], 'GSM5551708': [1.0], 'GSM5551709': [1.0], 'GSM5551710': [1.0], 'GSM5551711': [1.0], 'GSM5551712': [1.0], 'GSM5551713': [1.0], 'GSM5551714': [1.0], 'GSM5551715': [1.0]}\n",
"Clinical data shape: (1, 35)\n",
"Clinical features saved to ../../output/preprocess/Psoriasis/clinical_data/GSE183134.csv\n",
"Linking clinical and genetic data...\n",
"Linked data shape: (35, 22465)\n",
"Handling missing values...\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Data shape after handling missing values: (35, 22465)\n",
"\n",
"Checking for bias in feature variables:\n",
"For the feature 'Psoriasis', the least common label is '0.0' with 13 occurrences. This represents 37.14% of the dataset.\n",
"The distribution of the feature 'Psoriasis' in this dataset is fine.\n",
"\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Linked data saved to ../../output/preprocess/Psoriasis/GSE183134.csv\n",
"Final dataset shape: (35, 22465)\n"
]
}
],
"source": [
"# 1. Check if gene data is available after mapping\n",
"if gene_data.shape[0] == 0:\n",
" print(\"Error: Gene expression matrix is empty after mapping.\")\n",
" # Mark the dataset as not usable due to lack of gene expression data\n",
" is_usable = validate_and_save_cohort_info(\n",
" is_final=True,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=False, # No usable gene data\n",
" is_trait_available=True,\n",
" is_biased=True,\n",
" df=pd.DataFrame(),\n",
" note=\"Failed to map probe IDs to gene symbols. The annotation format may not be compatible with the extraction methods.\"\n",
" )\n",
" print(\"Dataset deemed not usable due to lack of gene expression data.\")\n",
"else:\n",
" # Only proceed with normalization if we have gene data\n",
" print(\"Normalizing gene symbols...\")\n",
" gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
" print(f\"Gene data shape after normalization: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n",
"\n",
" # Save the normalized gene data\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",
" # Extract clinical features from the original data source\n",
" print(\"Extracting clinical features from the original source...\")\n",
" # Get background information and clinical data again\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\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(\"Extracted clinical features preview:\")\n",
" print(preview_df(selected_clinical_df))\n",
" print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n",
" \n",
" # Save the extracted clinical features\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 features saved to {out_clinical_data_file}\")\n",
" \n",
" # Link clinical and genetic data\n",
" print(\"Linking clinical and genetic data...\")\n",
" linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data_normalized)\n",
" print(f\"Linked data shape: {linked_data.shape}\")\n",
" \n",
" # Check if the linked data has adequate data\n",
" if linked_data.shape[0] == 0 or linked_data.shape[1] <= 4: # 4 is an arbitrary small number\n",
" print(\"Error: Linked data has insufficient samples or features.\")\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=True,\n",
" df=linked_data,\n",
" note=\"Failed to properly link gene expression data with clinical features.\"\n",
" )\n",
" print(\"Dataset deemed not usable due to linking failure.\")\n",
" else:\n",
" # Handle missing values systematically\n",
" print(\"Handling missing values...\")\n",
" linked_data_clean = handle_missing_values(linked_data, trait_col=trait)\n",
" print(f\"Data shape after handling missing values: {linked_data_clean.shape}\")\n",
" \n",
" # Check if there are still samples after missing value handling\n",
" if linked_data_clean.shape[0] == 0:\n",
" print(\"Error: No samples remain after handling missing values.\")\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=True,\n",
" df=pd.DataFrame(),\n",
" note=\"All samples were removed during missing value handling.\"\n",
" )\n",
" print(\"Dataset deemed not usable as all samples were filtered out.\")\n",
" else:\n",
" # Check if the dataset is biased\n",
" print(\"\\nChecking for bias in feature variables:\")\n",
" is_biased, linked_data_final = judge_and_remove_biased_features(linked_data_clean, trait)\n",
" \n",
" # 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_final,\n",
" note=\"Dataset contains gene expression data for Crohn's Disease patients, examining response to Infliximab treatment.\"\n",
" )\n",
" \n",
" # Save linked data if usable\n",
" if is_usable:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" linked_data_final.to_csv(out_data_file)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
" print(f\"Final dataset shape: {linked_data_final.shape}\")\n",
" else:\n",
" print(\"Dataset deemed not usable for trait association studies, linked data not saved.\")"
]
}
],
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.16"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|