File size: 34,076 Bytes
32677ff |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "9ab1cdd8",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:20:29.658035Z",
"iopub.status.busy": "2025-03-25T08:20:29.657815Z",
"iopub.status.idle": "2025-03-25T08:20:29.823792Z",
"shell.execute_reply": "2025-03-25T08:20:29.823475Z"
}
},
"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 = \"Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
"cohort = \"GSE212331\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)\"\n",
"in_cohort_dir = \"../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE212331\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/GSE212331.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE212331.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE212331.csv\"\n",
"json_path = \"../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "7667d6d3",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "59e3b3aa",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:20:29.825132Z",
"iopub.status.busy": "2025-03-25T08:20:29.824994Z",
"iopub.status.idle": "2025-03-25T08:20:30.070099Z",
"shell.execute_reply": "2025-03-25T08:20:30.069789Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"Severity of lung function impairment drives transcriptional phenotypes of COPD and relates to immune and metabolic processes\"\n",
"!Series_summary\t\"Gene expression profiles were generated from induced sputum samples in COPD and healthy controls. The study identified transcriptional phenotypes of COPD.\"\n",
"!Series_overall_design\t\"This study used unsupervised hierarchical clustering of induced sputum gene expression profiles of 72 stable COPD patients and 15 healthy controls to identify distinct and clinically relevant transcriptional COPD phenotypes.\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['tissue: sputum'], 1: ['disease group: COPD', 'disease group: Healthy Control'], 2: ['gold stage: 2', 'gold stage: 3', 'gold stage: 4', 'gold stage: 1', 'gold stage: n/a'], 3: ['age: 75', 'age: 66', 'age: 83', 'age: 70', 'age: 61', 'age: 77', 'age: 64', 'age: 81', 'age: 60', 'age: 62', 'age: 80', 'age: 65', 'age: 74', 'age: 73', 'age: 54', 'age: 67', 'age: 72', 'age: 71', 'age: 82', 'age: 69', 'age: 63', 'age: 76', 'age: 68', 'age: 78', 'age: 84', 'age: 88', 'age: 79', 'age: 24', 'age: 21', 'age: 20'], 4: ['gender: Female', 'gender: Male']}\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": "16ab45cd",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "dbd7c2ae",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:20:30.071877Z",
"iopub.status.busy": "2025-03-25T08:20:30.071744Z",
"iopub.status.idle": "2025-03-25T08:20:30.082289Z",
"shell.execute_reply": "2025-03-25T08:20:30.082013Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Preview of extracted clinical features:\n",
"{0: [1.0, 75.0, 0.0]}\n",
"Clinical data saved to: ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/clinical_data/GSE212331.csv\n"
]
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this dataset appears to contain gene expression data from induced sputum samples\n",
"# The series title and summary explicitly mention \"gene expression profiles\" and not miRNA or methylation\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"# Trait (COPD): Available in row 1 \"disease group\"\n",
"trait_row = 1\n",
"\n",
"# Age: Available in row 3\n",
"age_row = 3\n",
"\n",
"# Gender: Available in row 4\n",
"gender_row = 4\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"def convert_trait(value):\n",
" \"\"\"\n",
" Convert COPD trait values to binary (0: Healthy Control, 1: COPD)\n",
" \"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" \n",
" value = value.strip().lower()\n",
" if \"disease group:\" in value:\n",
" value = value.split(\"disease group:\")[1].strip().lower()\n",
" \n",
" if \"copd\" in value:\n",
" return 1\n",
" elif \"healthy control\" in value or \"control\" in value:\n",
" return 0\n",
" else:\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" \"\"\"\n",
" Convert age values to continuous numeric values\n",
" \"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" \n",
" value = value.strip().lower()\n",
" if \"age:\" in value:\n",
" value = value.split(\"age:\")[1].strip()\n",
" \n",
" try:\n",
" return float(value)\n",
" except (ValueError, TypeError):\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" \"\"\"\n",
" Convert gender values to binary (0: Female, 1: Male)\n",
" \"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" \n",
" value = value.strip().lower()\n",
" if \"gender:\" in value:\n",
" value = value.split(\"gender:\")[1].strip().lower()\n",
" \n",
" if \"female\" in value or \"f\" in value:\n",
" return 0\n",
" elif \"male\" in value or \"m\" in value:\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Determine trait availability based on trait_row\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Initial filtering and saving 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",
"# We proceed with this step since trait_row is not None\n",
"if trait_row is not None:\n",
" # Create a DataFrame from the sample characteristics dictionary\n",
" # The sample characteristics dictionary was shown in the previous output\n",
" sample_chars = {\n",
" 0: ['tissue: sputum'], \n",
" 1: ['disease group: COPD', 'disease group: Healthy Control'], \n",
" 2: ['gold stage: 2', 'gold stage: 3', 'gold stage: 4', 'gold stage: 1', 'gold stage: n/a'], \n",
" 3: ['age: 75', 'age: 66', 'age: 83', 'age: 70', 'age: 61', 'age: 77', 'age: 64', 'age: 81', 'age: 60', \n",
" 'age: 62', 'age: 80', 'age: 65', 'age: 74', 'age: 73', 'age: 54', 'age: 67', 'age: 72', 'age: 71', \n",
" 'age: 82', 'age: 69', 'age: 63', 'age: 76', 'age: 68', 'age: 78', 'age: 84', 'age: 88', 'age: 79', \n",
" 'age: 24', 'age: 21', 'age: 20'], \n",
" 4: ['gender: Female', 'gender: Male']\n",
" }\n",
" \n",
" # Convert this dictionary to a DataFrame format that geo_select_clinical_features can process\n",
" # We need to create a DataFrame where each column is a sample and each row is a characteristic\n",
" # First, create a DataFrame with appropriate row indices\n",
" clinical_data = pd.DataFrame()\n",
" \n",
" # Populate the DataFrame with the sample characteristics\n",
" for row_idx, values in sample_chars.items():\n",
" row_data = pd.Series(values)\n",
" clinical_data[row_idx] = row_data\n",
" \n",
" # Transpose so each row is a characteristic\n",
" clinical_data = clinical_data.transpose()\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",
" # Preview the extracted clinical features\n",
" preview = preview_df(selected_clinical_df)\n",
" print(\"Preview of extracted clinical features:\")\n",
" print(preview)\n",
" \n",
" # Create directories if they don't exist\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" \n",
" # Save the clinical data to the specified output file\n",
" selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n",
" print(f\"Clinical data saved to: {out_clinical_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "d0034ca1",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "c6088560",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:20:30.083904Z",
"iopub.status.busy": "2025-03-25T08:20:30.083775Z",
"iopub.status.idle": "2025-03-25T08:20:30.542216Z",
"shell.execute_reply": "2025-03-25T08:20:30.541842Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Matrix file found: ../../input/GEO/Chronic_obstructive_pulmonary_disease_(COPD)/GSE212331/GSE212331_series_matrix.txt.gz\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene data shape: (47231, 87)\n",
"First 20 gene/probe identifiers:\n",
"Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n",
" 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n",
" 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n",
" 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n",
" 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n",
" dtype='object', name='ID')\n"
]
}
],
"source": [
"# 1. Get the SOFT and matrix file paths again \n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"print(f\"Matrix file found: {matrix_file}\")\n",
"\n",
"# 2. Use the get_genetic_data function from the library to get the gene_data\n",
"try:\n",
" gene_data = get_genetic_data(matrix_file)\n",
" print(f\"Gene data shape: {gene_data.shape}\")\n",
" \n",
" # 3. Print the first 20 row IDs (gene or probe identifiers)\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"
]
},
{
"cell_type": "markdown",
"id": "b0042e04",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "613a5940",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:20:30.543624Z",
"iopub.status.busy": "2025-03-25T08:20:30.543506Z",
"iopub.status.idle": "2025-03-25T08:20:30.545347Z",
"shell.execute_reply": "2025-03-25T08:20:30.545082Z"
}
},
"outputs": [],
"source": [
"# These identifiers are Illumina probe IDs (ILMN_* format) and not human gene symbols\n",
"# They need to be mapped to gene symbols for proper gene expression analysis\n",
"\n",
"requires_gene_mapping = True\n"
]
},
{
"cell_type": "markdown",
"id": "d563a8be",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "304dc5c9",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:20:30.547048Z",
"iopub.status.busy": "2025-03-25T08:20:30.546897Z",
"iopub.status.idle": "2025-03-25T08:20:39.371650Z",
"shell.execute_reply": "2025-03-25T08:20:39.371333Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Gene annotation preview:\n",
"Columns in gene annotation: ['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n",
"{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n",
"\n",
"Searching for platform information in SOFT file:\n",
"Platform ID not found in first 100 lines\n",
"\n",
"Searching for gene symbol information in SOFT file:\n",
"Found references to gene symbols:\n",
"#ILMN_Gene = Internal gene symbol\n",
"#Symbol = Gene symbol from the source database\n",
"#Synonyms = Gene symbol synonyms from Refseq\n",
"ID\tSpecies\tSource\tSearch_Key\tTranscript\tILMN_Gene\tSource_Reference_ID\tRefSeq_ID\tUnigene_ID\tEntrez_Gene_ID\tGI\tAccession\tSymbol\tProtein_Product\tProbe_Id\tArray_Address_Id\tProbe_Type\tProbe_Start\tSEQUENCE\tChromosome\tProbe_Chr_Orientation\tProbe_Coordinates\tCytoband\tDefinition\tOntology_Component\tOntology_Process\tOntology_Function\tSynonyms\tObsolete_Probe_Id\tGB_ACC\n",
"ILMN_1651228\tHomo sapiens\tRefSeq\tNM_001031.4\tILMN_992\tRPS28\tNM_001031.4\tNM_001031.4\t\t6234\t71565158\tNM_001031.4\tRPS28\tNP_001022.1\tILMN_1651228\t650349\tS\t329\tCGCCACACGTAACTGAGATGCTCCTTTAAATAAAGCGTTTGTGTTTCAAG\t19\t+\t8293227-8293276\t19p13.2d\t\"Homo sapiens ribosomal protein S28 (RPS28), mRNA.\"\t\"The living contents of a cell; the matter contained within (but not including) the plasma membrane, usually taken to exclude large vacuoles and masses of secretory or ingested material. In eukaryotes it includes the nucleus and cytoplasm [goid 5622] [evidence IEA]; That part of the cytoplasm that does not contain membranous or particulate subcellular components [goid 5829] [pmid 12588972] [evidence EXP]; An intracellular organelle, about 200 A in diameter, consisting of RNA and protein. It is the site of protein biosynthesis resulting from translation of messenger RNA (mRNA). It consists of two subunits, one large and one small, each containing only protein and RNA. Both the ribosome and its subunits are characterized by their sedimentation coefficients, expressed in Svedberg units (symbol: S). Hence, the prokaryotic ribosome (70S) comprises a large (50S) subunit and a small (30S) subunit, while the eukaryotic ribosome (80S) comprises a large (60S) subunit and a small (40S) subunit. Two sites on the ribosomal large subunit are involved in translation, namely the aminoacyl site (A site) and peptidyl site (P site). Ribosomes from prokaryotes, eukaryotes, mitochondria, and chloroplasts have characteristically distinct ribosomal proteins [goid 5840] [evidence IEA]; The small subunit of the ribosome that is found in the cytosol of the cell. The cytosol is that part of the cytoplasm that does not contain membranous or particulate subcellular components [goid 22627] [pmid 15883184] [evidence IDA]\"\tThe successive addition of amino acid residues to a nascent polypeptide chain during protein biosynthesis [goid 6414] [pmid 15189156] [evidence EXP]\tThe action of a molecule that contributes to the structural integrity of the ribosome [goid 3735] [pmid 15883184] [evidence IDA]; Interacting selectively with any protein or protein complex (a complex of two or more proteins that may include other nonprotein molecules) [goid 5515] [pmid 17353931] [evidence IPI]\t\t\tNM_001031.4\n",
"\n",
"Checking for additional annotation files in the directory:\n",
"[]\n"
]
}
],
"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. 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=5))\n",
"\n",
"# Let's look for platform information in the SOFT file to understand the annotation better\n",
"print(\"\\nSearching for platform information in SOFT file:\")\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" for i, line in enumerate(f):\n",
" if '!Series_platform_id' in line:\n",
" print(line.strip())\n",
" break\n",
" if i > 100: # Limit search to first 100 lines\n",
" print(\"Platform ID not found in first 100 lines\")\n",
" break\n",
"\n",
"# Check if the SOFT file includes any reference to gene symbols\n",
"print(\"\\nSearching for gene symbol information in SOFT file:\")\n",
"with gzip.open(soft_file, 'rt') as f:\n",
" gene_symbol_lines = []\n",
" for i, line in enumerate(f):\n",
" if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n",
" gene_symbol_lines.append(line.strip())\n",
" if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n",
" break\n",
" \n",
" if gene_symbol_lines:\n",
" print(\"Found references to gene symbols:\")\n",
" for line in gene_symbol_lines[:5]: # Show just first 5 matches\n",
" print(line)\n",
" else:\n",
" print(\"No explicit gene symbol references found in first 1000 lines\")\n",
"\n",
"# Look for alternative annotation files or references in the directory\n",
"print(\"\\nChecking for additional annotation files in the directory:\")\n",
"all_files = os.listdir(in_cohort_dir)\n",
"print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n"
]
},
{
"cell_type": "markdown",
"id": "50c931cb",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "cc36bcae",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:20:39.373531Z",
"iopub.status.busy": "2025-03-25T08:20:39.373382Z",
"iopub.status.idle": "2025-03-25T08:20:40.834339Z",
"shell.execute_reply": "2025-03-25T08:20:40.834014Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene mapping dataframe shape: (44837, 2)\n",
"Sample of gene mapping:\n",
" ID Gene\n",
"0 ILMN_1343048 phage_lambda_genome\n",
"1 ILMN_1343049 phage_lambda_genome\n",
"2 ILMN_1343050 phage_lambda_genome:low\n",
"3 ILMN_1343052 phage_lambda_genome:low\n",
"4 ILMN_1343059 thrB\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene-level expression data shape: (21372, 87)\n",
"First few gene symbols:\n",
"Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n",
" 'A4GALT', 'A4GNT'],\n",
" dtype='object', name='Gene')\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"After normalizing gene symbols, expression data shape: (20259, 87)\n",
"First few normalized gene symbols:\n",
"Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT',\n",
" 'A4GNT', 'AAA1', 'AAAS'],\n",
" dtype='object', name='Gene')\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene expression data saved to: ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/gene_data/GSE212331.csv\n"
]
}
],
"source": [
"# 1. Identify columns for gene identifiers and gene symbols in the annotation data\n",
"# Based on the preview, we can see:\n",
"# - 'ID' column contains Illumina probe IDs (ILMN_*) which match our gene expression data indices\n",
"# - 'Symbol' column contains gene symbols \n",
"\n",
"# 2. Get gene mapping dataframe by extracting the relevant columns\n",
"gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
"print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
"print(\"Sample of gene mapping:\")\n",
"print(gene_mapping.head())\n",
"\n",
"# 3. Apply gene mapping to convert probe-level measurements to gene-level expression\n",
"gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
"print(f\"Gene-level expression data shape: {gene_data.shape}\")\n",
"print(\"First few gene symbols:\")\n",
"print(gene_data.index[:10])\n",
"\n",
"# Normalize gene symbols to handle synonyms and standardize\n",
"gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"After normalizing gene symbols, expression data shape: {gene_data.shape}\")\n",
"print(\"First few normalized gene symbols:\")\n",
"print(gene_data.index[:10])\n",
"\n",
"# Save the gene data to the specified output 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": "c4f676f5",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "14c941be",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:20:40.836183Z",
"iopub.status.busy": "2025-03-25T08:20:40.836030Z",
"iopub.status.idle": "2025-03-25T08:20:54.889084Z",
"shell.execute_reply": "2025-03-25T08:20:54.888706Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalized gene data shape: (20259, 87)\n",
"Gene data column names (sample IDs):\n",
"Index(['GSM6524456', 'GSM6524458', 'GSM6524459', 'GSM6524460', 'GSM6524462'], dtype='object')\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Raw clinical data structure:\n",
"Clinical data shape: (5, 88)\n",
"Clinical data columns: Index(['!Sample_geo_accession', 'GSM6524456', 'GSM6524458', 'GSM6524459',\n",
" 'GSM6524460'],\n",
" dtype='object')\n",
"\n",
"Sample characteristics dictionary:\n",
"{0: ['tissue: sputum'], 1: ['disease group: COPD', 'disease group: Healthy Control'], 2: ['gold stage: 2', 'gold stage: 3', 'gold stage: 4', 'gold stage: 1', 'gold stage: n/a'], 3: ['age: 75', 'age: 66', 'age: 83', 'age: 70', 'age: 61', 'age: 77', 'age: 64', 'age: 81', 'age: 60', 'age: 62', 'age: 80', 'age: 65', 'age: 74', 'age: 73', 'age: 54', 'age: 67', 'age: 72', 'age: 71', 'age: 82', 'age: 69', 'age: 63', 'age: 76', 'age: 68', 'age: 78', 'age: 84', 'age: 88', 'age: 79', 'age: 24', 'age: 21', 'age: 20'], 4: ['gender: Female', 'gender: Male']}\n",
"\n",
"Values in trait row:\n",
"['!Sample_characteristics_ch1' 'disease group: COPD' 'disease group: COPD'\n",
" 'disease group: COPD' 'disease group: COPD']\n",
"\n",
"Created clinical features dataframe:\n",
"Shape: (1, 87)\n",
" GSM6524456 GSM6524458 GSM6524459 \\\n",
"Chronic_obstructive_pulmonary_disease_(COPD) 1 1 1 \n",
"\n",
" GSM6524460 GSM6524462 \n",
"Chronic_obstructive_pulmonary_disease_(COPD) 1 1 \n",
"\n",
"Linked data shape before handling missing values: (87, 20260)\n",
"Actual trait column in linked data: Chronic_obstructive_pulmonary_disease_(COPD)\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n",
" df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Linked data shape after handling missing values: (87, 20260)\n",
"For the feature 'Chronic_obstructive_pulmonary_disease_(COPD)', the least common label is '0' with 15 occurrences. This represents 17.24% of the dataset.\n",
"The distribution of the feature 'Chronic_obstructive_pulmonary_disease_(COPD)' in this dataset is fine.\n",
"\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Linked data saved to ../../output/preprocess/Chronic_obstructive_pulmonary_disease_(COPD)/GSE212331.csv\n"
]
}
],
"source": [
"# 1. Normalize gene symbols in the gene expression data \n",
"# (This was already done in the previous step, so no need to repeat)\n",
"print(f\"Normalized gene data shape: {gene_data.shape}\")\n",
"\n",
"# 2. Examine the sample IDs in the gene expression data to understand the structure\n",
"print(\"Gene data column names (sample IDs):\")\n",
"print(gene_data.columns[:5]) # Print first 5 for brevity\n",
"\n",
"# Inspect the clinical data format from the matrix file directly\n",
"background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
"print(\"\\nRaw clinical data structure:\")\n",
"print(f\"Clinical data shape: {clinical_data.shape}\")\n",
"print(f\"Clinical data columns: {clinical_data.columns[:5]}\")\n",
"\n",
"# Get the sample characteristics to re-extract the disease information\n",
"sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
"print(\"\\nSample characteristics dictionary:\")\n",
"print(sample_characteristics_dict)\n",
"\n",
"# 3. Directly create clinical features from the raw data again\n",
"# Verify trait row contains the disease information (OA vs RA)\n",
"print(\"\\nValues in trait row:\")\n",
"trait_values = clinical_data.iloc[trait_row].values\n",
"print(trait_values[:5])\n",
"\n",
"# Create clinical dataframe with proper structure\n",
"# First get the sample IDs from gene data as these are our actual sample identifiers\n",
"sample_ids = gene_data.columns.tolist()\n",
"\n",
"# Create the clinical features dataframe with those sample IDs\n",
"clinical_features = pd.DataFrame(index=[trait], columns=sample_ids)\n",
"\n",
"# Fill the clinical features with our trait values by mapping GSM IDs to actual values\n",
"for col in clinical_data.columns:\n",
" if col in sample_ids:\n",
" # Extract the disease value and convert it\n",
" disease_val = clinical_data.iloc[trait_row][col]\n",
" clinical_features.loc[trait, col] = convert_trait(disease_val)\n",
"\n",
"print(\"\\nCreated clinical features dataframe:\")\n",
"print(f\"Shape: {clinical_features.shape}\")\n",
"print(clinical_features.iloc[:, :5]) # Show first 5 columns\n",
"\n",
"# 4. Link clinical and genetic data\n",
"linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
"print(f\"\\nLinked data shape before handling missing values: {linked_data.shape}\")\n",
"\n",
"# 5. Handle missing values - we need to use the actual column name, not the trait variable\n",
"# First identify the actual trait column name in the linked data\n",
"trait_column = clinical_features.index[0] # This should be 'Osteoarthritis'\n",
"print(f\"Actual trait column in linked data: {trait_column}\")\n",
"\n",
"# Now handle missing values with the correct column name\n",
"linked_data_clean = handle_missing_values(linked_data, trait_column)\n",
"print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n",
"\n",
"# 6. Evaluate bias in trait and demographic features\n",
"is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait_column)\n",
"\n",
"# 7. Conduct final quality validation\n",
"note = \"Dataset contains gene expression data from synovial fibroblasts of RA and OA patients. Data includes high serum and low serum responses.\"\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=(linked_data_clean.shape[0] > 0),\n",
" is_biased=is_biased,\n",
" df=linked_data_clean,\n",
" note=note\n",
")\n",
"\n",
"# 8. Save linked data if usable\n",
"if is_usable:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" linked_data_clean.to_csv(out_data_file)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
"else:\n",
" print(\"Dataset deemed not usable due to quality issues - 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
}
|