File size: 33,024 Bytes
e4183cf |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "92789792",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:26.480037Z",
"iopub.status.busy": "2025-03-25T08:31:26.479585Z",
"iopub.status.idle": "2025-03-25T08:31:26.643901Z",
"shell.execute_reply": "2025-03-25T08:31:26.643580Z"
}
},
"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 = \"COVID-19\"\n",
"cohort = \"GSE216705\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/COVID-19\"\n",
"in_cohort_dir = \"../../input/GEO/COVID-19/GSE216705\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/COVID-19/GSE216705.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE216705.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE216705.csv\"\n",
"json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "4e575dcb",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "07f964d6",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:26.645232Z",
"iopub.status.busy": "2025-03-25T08:31:26.645100Z",
"iopub.status.idle": "2025-03-25T08:31:26.742874Z",
"shell.execute_reply": "2025-03-25T08:31:26.742589Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"Loss of GM-CSF-dependent instruction of alveolar macrophages in COVID-19 provides a rationale for inhaled GM-CSF treatment\"\n",
"!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n",
"!Series_overall_design\t\"Refer to individual Series\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['strain: C57BL/6'], 1: ['metadata info: metaData_microarrays.txt']}\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": "cddfa4a5",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "785a9429",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:26.743921Z",
"iopub.status.busy": "2025-03-25T08:31:26.743820Z",
"iopub.status.idle": "2025-03-25T08:31:26.750213Z",
"shell.execute_reply": "2025-03-25T08:31:26.749941Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Based on the background information and sample characteristics, let's analyze this dataset\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# The background information about \"Loss of GM-CSF-dependent instruction of alveolar macrophages in COVID-19\"\n",
"# suggests this is likely a gene expression dataset studying COVID-19's effects\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# Looking at the sample characteristics dictionary, we don't see typical human clinical data\n",
"# The dict shows 'strain: C57BL/6' which indicates this is likely a mouse model study, not human data\n",
"# and 'metadata info: metaData_microarrays.txt' which refers to external metadata\n",
"\n",
"# 2.1 Data Availability\n",
"# Since we don't see trait, age, or gender data in the sample characteristics,\n",
"# we'll set all row identifiers to None\n",
"trait_row = None # No COVID-19 status information in the sample characteristics\n",
"age_row = None # No age information in the sample characteristics\n",
"gender_row = None # No gender information in the sample characteristics\n",
"\n",
"# 2.2 Data Type Conversion\n",
"# Define conversion functions in case they're needed, even though we don't have the data\n",
"def convert_trait(value):\n",
" if value is None:\n",
" return None\n",
" value = value.split(\":\")[-1].strip() if \":\" in value else value.strip()\n",
" if value.lower() in [\"covid-19\", \"positive\", \"covid\", \"yes\"]:\n",
" return 1\n",
" elif value.lower() in [\"healthy\", \"control\", \"negative\", \"no\"]:\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" if value is None:\n",
" return None\n",
" value = value.split(\":\")[-1].strip() if \":\" in value else value.strip()\n",
" try:\n",
" return float(value)\n",
" except ValueError:\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" if value is None:\n",
" return None\n",
" value = value.split(\":\")[-1].strip() if \":\" in value else value.strip()\n",
" if value.lower() in [\"female\", \"f\"]:\n",
" return 0\n",
" elif value.lower() in [\"male\", \"m\"]:\n",
" return 1\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Trait data is not available since trait_row is None\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Save initial usability information\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",
"# Since trait_row is None, we'll skip this substep\n",
"# If trait_row was not None, we would have executed:\n",
"# clinical_df = geo_select_clinical_features(\n",
"# clinical_df=clinical_data,\n",
"# trait=trait,\n",
"# trait_row=trait_row,\n",
"# convert_trait=convert_trait,\n",
"# age_row=age_row,\n",
"# convert_age=convert_age,\n",
"# gender_row=gender_row,\n",
"# convert_gender=convert_gender\n",
"# )\n",
"# preview_df(clinical_df)\n",
"# clinical_df.to_csv(out_clinical_data_file)\n"
]
},
{
"cell_type": "markdown",
"id": "a619f55c",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "61a1e12e",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:26.751206Z",
"iopub.status.busy": "2025-03-25T08:31:26.751107Z",
"iopub.status.idle": "2025-03-25T08:31:26.871768Z",
"shell.execute_reply": "2025-03-25T08:31:26.871401Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"SOFT file: ../../input/GEO/COVID-19/GSE216705/GSE216705_family.soft.gz\n",
"Matrix file: ../../input/GEO/COVID-19/GSE216705/GSE216705-GPL6246_series_matrix.txt.gz\n",
"Found the matrix table marker at line 62\n",
"Gene data shape: (35556, 27)\n",
"First 20 gene/probe identifiers:\n",
"['10338001', '10338002', '10338003', '10338004', '10338005', '10338006', '10338007', '10338008', '10338009', '10338010', '10338011', '10338012', '10338013', '10338014', '10338015', '10338016', '10338017', '10338018', '10338019', '10338020']\n"
]
}
],
"source": [
"# 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",
"print(f\"SOFT file: {soft_file}\")\n",
"print(f\"Matrix file: {matrix_file}\")\n",
"\n",
"# Set gene availability flag\n",
"is_gene_available = True # Initially assume gene data is available\n",
"\n",
"# First check if the matrix file contains the expected marker\n",
"found_marker = False\n",
"marker_row = None\n",
"try:\n",
" with gzip.open(matrix_file, 'rt') as file:\n",
" for i, line in enumerate(file):\n",
" if \"!series_matrix_table_begin\" in line:\n",
" found_marker = True\n",
" marker_row = i\n",
" print(f\"Found the matrix table marker at line {i}\")\n",
" break\n",
" \n",
" if not found_marker:\n",
" print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
" is_gene_available = False\n",
" \n",
" # If marker was found, try to extract gene data\n",
" if is_gene_available:\n",
" try:\n",
" # Try using the library function\n",
" gene_data = get_genetic_data(matrix_file)\n",
" \n",
" if gene_data.shape[0] == 0:\n",
" print(\"Warning: Extracted gene data has 0 rows.\")\n",
" is_gene_available = False\n",
" else:\n",
" print(f\"Gene data shape: {gene_data.shape}\")\n",
" # Print the first 20 gene/probe identifiers\n",
" print(\"First 20 gene/probe identifiers:\")\n",
" print(gene_data.index[:20].tolist())\n",
" except Exception as e:\n",
" print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
" is_gene_available = False\n",
" \n",
" # If gene data extraction failed, examine file content to diagnose\n",
" if not is_gene_available:\n",
" print(\"Examining file content to diagnose the issue:\")\n",
" try:\n",
" with gzip.open(matrix_file, 'rt') as file:\n",
" # Print lines around the marker if found\n",
" if marker_row is not None:\n",
" for i, line in enumerate(file):\n",
" if i >= marker_row - 2 and i <= marker_row + 10:\n",
" print(f\"Line {i}: {line.strip()[:100]}...\")\n",
" if i > marker_row + 10:\n",
" break\n",
" else:\n",
" # If marker not found, print first 10 lines\n",
" for i, line in enumerate(file):\n",
" if i < 10:\n",
" print(f\"Line {i}: {line.strip()[:100]}...\")\n",
" else:\n",
" break\n",
" except Exception as e2:\n",
" print(f\"Error examining file: {e2}\")\n",
" \n",
"except Exception as e:\n",
" print(f\"Error processing file: {e}\")\n",
" is_gene_available = False\n",
"\n",
"# Update validation information if gene data extraction failed\n",
"if not is_gene_available:\n",
" print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
" # Update the validation record since gene data isn't available\n",
" is_trait_available = False # We already determined trait data isn't available in step 2\n",
" validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
" is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
]
},
{
"cell_type": "markdown",
"id": "7d3bf662",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "109711f3",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:26.873008Z",
"iopub.status.busy": "2025-03-25T08:31:26.872888Z",
"iopub.status.idle": "2025-03-25T08:31:26.874784Z",
"shell.execute_reply": "2025-03-25T08:31:26.874514Z"
}
},
"outputs": [],
"source": [
"# Analyzing the gene identifiers provided in the previous output\n",
"# The identifiers appear to be probe IDs (numeric format like '10338001') rather than standard human gene symbols\n",
"# Human gene symbols typically follow patterns like \"BRCA1\", \"TP53\", etc.\n",
"# These numeric identifiers need to be mapped to human gene symbols for meaningful analysis\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "d9a0110e",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "95a5c320",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:26.875855Z",
"iopub.status.busy": "2025-03-25T08:31:26.875753Z",
"iopub.status.idle": "2025-03-25T08:31:29.190497Z",
"shell.execute_reply": "2025-03-25T08:31:29.190121Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Gene annotation preview:\n",
"Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n",
"{'ID': ['10344614', '10344616', '10344618'], 'GB_LIST': ['AK145513,AK145782', nan, nan], 'SPOT_ID': ['chr1:3054233-3054733', 'chr1:3102016-3102125', 'chr1:3276323-3277348'], 'seqname': ['chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000067.6', 'NC_000067.6', 'NC_000067.6'], 'RANGE_STRAND': ['+', '+', '+'], 'RANGE_START': ['3054233', '3102016', '3276323'], 'RANGE_STOP': ['3054733', '3102125', '3277348'], 'total_probes': [33.0, 25.0, 25.0], 'gene_assignment': ['ENSMUST00000160944 // Gm16088 // predicted gene 16088 // --- // --- /// ENSMUST00000120800 // Gm14300 // predicted gene 14300 // --- // --- /// ENSMUST00000179907 // G430049J08Rik // RIKEN cDNA G430049J08 gene // --- // --- /// AK145513 // Gm2889 // predicted gene 2889 // 18 A1|18 // 100040658', 'ENSMUST00000082908 // Gm26206 // predicted gene, 26206 // --- // ---', '---'], 'mrna_assignment': ['ENSMUST00000160944 // ENSEMBL // havana:known chromosome:GRCm38:1:3054233:3054733:1 gene:ENSMUSG00000090025 gene_biotype:pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 33 // 33 // 0 /// ENSMUST00000120800 // ENSEMBL // havana:known chromosome:GRCm38:2:179612622:179613567:-1 gene:ENSMUSG00000083410 gene_biotype:pseudogene transcript_biotype:processed_pseudogene // chr1 // 30 // 100 // 10 // 33 // 0 /// ENSMUST00000179907 // ENSEMBL // ensembl:known chromosome:GRCm38:18:3471630:3474315:1 gene:ENSMUSG00000096528 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 42 // 100 // 14 // 33 // 0 /// AK145513 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0009C06 product:hypothetical DeoxyUTP pyrophosphatase/Aspartyl protease, retroviral-type family profile/Retrovirus capsid, C-terminal/Peptidase aspartic/Peptidase aspartic, active site containing protein, full insert sequence. // chr1 // 24 // 100 // 8 // 33 // 0 /// AK145782 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0042P10 product:hypothetical protein, full insert sequence. // chr1 // 52 // 100 // 17 // 33 // 0 /// KnowTID_00005135 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 52 // 100 // 17 // 33 // 0 /// NONMMUT044096 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 52 // 100 // 17 // 33 // 0 /// AK139746 // GenBank HTC // Mus musculus 2 cells egg cDNA, RIKEN full-length enriched library, clone:B020014N01 product:hypothetical protein, full insert sequence. // chr1 // 42 // 100 // 14 // 33 // 0 /// AK145590 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0019N16 product:unclassifiable, full insert sequence. // chr1 // 42 // 100 // 14 // 33 // 0 /// AK145750 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0037K09 product:unclassifiable, full insert sequence. // chr1 // 36 // 85 // 10 // 28 // 0 /// AK165162 // GenBank HTC // Mus musculus 8 cells embryo 8 cells cDNA, RIKEN full-length enriched library, clone:E860009L19 product:unclassifiable, full insert sequence. // chr1 // 48 // 100 // 16 // 33 // 0 /// KnowTID_00001379 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 42 // 100 // 14 // 33 // 0 /// KnowTID_00001380 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 42 // 100 // 14 // 33 // 0 /// KnowTID_00002541 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 36 // 85 // 10 // 28 // 0 /// KnowTID_00003768 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 42 // 100 // 14 // 33 // 0 /// KnowTID_00005134 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 45 // 100 // 15 // 33 // 0 /// NONMMUT013638 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 42 // 100 // 14 // 33 // 0 /// NONMMUT013641 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 42 // 100 // 14 // 33 // 0 /// NONMMUT021887 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 36 // 85 // 10 // 28 // 0 /// NONMMUT044095 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 45 // 100 // 15 // 33 // 0 /// NONMMUT046086 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 48 // 100 // 16 // 33 // 0 /// NONMMUT046087 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 48 // 100 // 16 // 33 // 0 /// AK145700 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0031F10 product:hypothetical protein, full insert sequence. // chr1 // 24 // 100 // 8 // 33 // 0 /// KnowTID_00003789 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 24 // 100 // 8 // 33 // 0 /// NONMMUT031618 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 24 // 100 // 8 // 33 // 0 /// KnowTID_00002704 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 24 // 24 // 8 // 33 // 1 /// NONMMUT023055 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 24 // 24 // 8 // 33 // 1', 'ENSMUST00000082908 // ENSEMBL // ncrna:known chromosome:GRCm38:1:3102016:3102125:1 gene:ENSMUSG00000064842 gene_biotype:snRNA transcript_biotype:snRNA // chr1 // 100 // 100 // 25 // 25 // 0 /// NONMMUT000002 // NONCODE // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 25 // 25 // 0', '---'], 'category': ['main', 'main', 'main']}\n",
"\n",
"Examining 'gene_assignment' column examples:\n",
"Example 1: ENSMUST00000160944 // Gm16088 // predicted gene 16088 // --- // --- /// ENSMUST00000120800 // Gm14300 // predicted gene 14300 // --- // --- /// ENSMUST00000179907 // G430049J08Rik // RIKEN cDNA G43004...\n",
"Example 2: ENSMUST00000082908 // Gm26206 // predicted gene, 26206 // --- // ---\n",
"Example 3: ---\n",
"Example 4: AK140060 // Gm10568 // predicted gene 10568 // --- // 100038431\n",
"Example 5: ---\n",
"\n",
"Gene assignment column completeness: 35556/995596 rows (3.57%)\n",
"Probes without gene assignments: 8197/995596 rows (0.82%)\n",
"\n",
"Columns identified for gene mapping:\n",
"- 'ID': Contains probe IDs (e.g., 7896736)\n",
"- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\n"
]
}
],
"source": [
"# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"gene_annotation = get_gene_annotation(soft_file)\n",
"\n",
"# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n",
"print(\"\\nGene annotation preview:\")\n",
"print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n",
"print(preview_df(gene_annotation, n=3))\n",
"\n",
"# Examining the gene_assignment column which appears to contain gene symbol information\n",
"print(\"\\nExamining 'gene_assignment' column examples:\")\n",
"if 'gene_assignment' in gene_annotation.columns:\n",
" # Display a few examples of the gene_assignment column to understand its format\n",
" gene_samples = gene_annotation['gene_assignment'].head(5).tolist()\n",
" for i, sample in enumerate(gene_samples):\n",
" print(f\"Example {i+1}: {sample[:200]}...\" if isinstance(sample, str) and len(sample) > 200 else f\"Example {i+1}: {sample}\")\n",
" \n",
" # Check the quality and completeness of the gene_assignment column\n",
" non_null_assignments = gene_annotation['gene_assignment'].notna().sum()\n",
" total_rows = len(gene_annotation)\n",
" print(f\"\\nGene assignment column completeness: {non_null_assignments}/{total_rows} rows ({non_null_assignments/total_rows:.2%})\")\n",
" \n",
" # Check for probe IDs without gene assignments (typically '---' entries)\n",
" missing_assignments = gene_annotation[gene_annotation['gene_assignment'] == '---'].shape[0]\n",
" print(f\"Probes without gene assignments: {missing_assignments}/{total_rows} rows ({missing_assignments/total_rows:.2%})\")\n",
" \n",
" # Identify the columns needed for gene mapping\n",
" print(\"\\nColumns identified for gene mapping:\")\n",
" print(\"- 'ID': Contains probe IDs (e.g., 7896736)\")\n",
" print(\"- 'gene_assignment': Contains gene information that needs parsing to extract gene symbols\")\n",
"else:\n",
" print(\"Error: 'gene_assignment' column not found in annotation data.\")\n",
" print(\"Available columns:\", gene_annotation.columns.tolist())\n"
]
},
{
"cell_type": "markdown",
"id": "e9b7fd0f",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "b706a199",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:29.191822Z",
"iopub.status.busy": "2025-03-25T08:31:29.191707Z",
"iopub.status.idle": "2025-03-25T08:31:30.356745Z",
"shell.execute_reply": "2025-03-25T08:31:30.356378Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene expression data shape: (35556, 27)\n",
"Sample gene expression IDs: ['10338001', '10338002', '10338003', '10338004', '10338005']\n",
"Creating gene mapping dataframe...\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Mapping dataframe shape: (290501, 2)\n",
"Sample mapping entries:\n",
" ID Gene\n",
"0 10344614 Gm16088\n",
"0 10344614 Gm14300\n",
"0 10344614 G430049J08Rik\n",
"0 10344614 Gm2889\n",
"1 10344616 Gm26206\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene expression data after mapping: (290, 27)\n",
"Sample gene symbols: ['A330087I24', 'A730034C02', 'AA066038', 'AA386476', 'AA388235', 'AA414768', 'AA415398', 'AA467197', 'AA474408', 'AA667203']\n",
"Gene expression data saved to ../../output/preprocess/COVID-19/gene_data/GSE216705.csv\n"
]
}
],
"source": [
"# Check the format of IDs in our gene expression data\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"gene_data = get_genetic_data(matrix_file)\n",
"print(f\"Gene expression data shape: {gene_data.shape}\")\n",
"print(f\"Sample gene expression IDs: {gene_data.index[:5].tolist()}\")\n",
"\n",
"# Extract the mapping between probe IDs and gene symbols\n",
"# Based on the previous output, we need the 'ID' column (probe identifiers) and 'gene_assignment' column (gene symbols)\n",
"print(\"Creating gene mapping dataframe...\")\n",
"\n",
"# Create a function to extract gene symbols from gene_assignment string\n",
"def extract_gene_symbols(gene_assignment_str):\n",
" if not isinstance(gene_assignment_str, str) or gene_assignment_str == '---':\n",
" return []\n",
" \n",
" # The format appears to be \"ENSMUST... // GeneName // description // --- // ---\"\n",
" # We want to extract the gene names (second element after '//')\n",
" genes = []\n",
" assignments = gene_assignment_str.split('///')\n",
" for assignment in assignments:\n",
" parts = assignment.strip().split('//')\n",
" if len(parts) >= 2:\n",
" gene_symbol = parts[1].strip()\n",
" if gene_symbol and gene_symbol != '---':\n",
" genes.append(gene_symbol)\n",
" return genes\n",
"\n",
"# Apply extraction function to create mapping dataframe\n",
"gene_annotation['Genes'] = gene_annotation['gene_assignment'].apply(extract_gene_symbols)\n",
"valid_rows = gene_annotation['Genes'].apply(len) > 0\n",
"mapping_df = gene_annotation.loc[valid_rows, ['ID', 'Genes']]\n",
"mapping_df = mapping_df.explode('Genes')\n",
"mapping_df = mapping_df.rename(columns={'Genes': 'Gene'})\n",
"print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n",
"print(\"Sample mapping entries:\")\n",
"print(mapping_df.head())\n",
"\n",
"# Apply gene mapping to convert probe-level measurements to gene expression data\n",
"gene_data = apply_gene_mapping(gene_data, mapping_df)\n",
"print(f\"Gene expression data after mapping: {gene_data.shape}\")\n",
"print(f\"Sample gene symbols: {gene_data.index[:10].tolist()}\")\n",
"\n",
"# Save the gene expression data\n",
"if gene_data.shape[0] > 0:\n",
" # Create directory if it doesn't exist\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",
"else:\n",
" print(\"No gene expression data to save after mapping.\")\n"
]
},
{
"cell_type": "markdown",
"id": "d3de0ce4",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "d50710f1",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:30.358105Z",
"iopub.status.busy": "2025-03-25T08:31:30.357987Z",
"iopub.status.idle": "2025-03-25T08:31:30.432674Z",
"shell.execute_reply": "2025-03-25T08:31:30.432306Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene data shape after normalization: (34, 27)\n",
"Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE216705.csv\n",
"No clinical features available, skipping clinical data processing.\n",
"Abnormality detected in the cohort: GSE216705. Preprocessing failed.\n",
"Linked data not saved due to quality issues or missing trait information.\n"
]
}
],
"source": [
"# 1. Normalize gene symbols in the gene expression data\n",
"normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
"\n",
"# Create output directory if it doesn't exist\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"\n",
"# Save the 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",
"\n",
"# Determine if trait data is available\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Skip clinical processing if trait_row is None\n",
"if is_trait_available:\n",
" # 2. Extract clinical features using the previously identified feature rows\n",
" clinical_features = geo_select_clinical_features(\n",
" 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",
" # Create directory for clinical data output\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" \n",
" # Save the clinical features\n",
" clinical_features.to_csv(out_clinical_data_file)\n",
" print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
" \n",
" # Preview the clinical features\n",
" clinical_features_preview = preview_df(clinical_features.T)\n",
" print(\"Clinical features preview:\")\n",
" print(clinical_features_preview)\n",
" \n",
" # 3. Link clinical and genetic data\n",
" linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n",
" print(f\"Linked data shape: {linked_data.shape}\")\n",
" \n",
" # 4. Handle missing values in the linked data\n",
" linked_data = handle_missing_values(linked_data, trait)\n",
" print(f\"Linked 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",
"else:\n",
" print(\"No clinical features available, skipping clinical data processing.\")\n",
" # Create a minimal DataFrame with the trait column\n",
" linked_data = pd.DataFrame({trait: []})\n",
" is_biased = True # Set to True because without trait data, it's unusable\n",
"\n",
"# 6. Validate and save cohort info\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=\"Dataset contains mouse gene expression data but lacks human clinical annotations for COVID-19.\"\n",
")\n",
"\n",
"# 7. Save the linked data if it's usable\n",
"if is_usable and is_trait_available:\n",
" # Create output directory if it doesn't exist\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" \n",
" # Save the linked data\n",
" linked_data.to_csv(out_data_file)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
"else:\n",
" print(\"Linked data not saved due to quality issues or missing trait information.\")"
]
}
],
"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
}
|